本文整理汇总了Python中hasattr函数的典型用法代码示例。如果您正苦于以下问题:Python hasattr函数的具体用法?Python hasattr怎么用?Python hasattr使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了hasattr函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: check_server_disallowed
def check_server_disallowed(self):
"""
Check if server domain name or IP is disallowed in settings.py.
"""
hostname = self.netloc_parts[2].lower()
if (hasattr(settings, 'DISALLOWED_DOMAIN_LIST') and
settings.DISALLOWED_DOMAIN_LIST):
for domain in settings.DISALLOWED_DOMAIN_LIST:
if hostname == domain or hostname.endswith('.' + domain):
raise ValidationError(unicode(
_("Domain name %(domain)s is disallowed.") % locals()))
try:
ip = socket.gethostbyname(hostname)
except socket.error:
raise ValidationError(unicode(
_("Could not resolve IP address for %(hostname)s.") %
locals()))
if (not hasattr(settings, 'DISALLOWED_SERVER_IP_LIST') or
not settings.DISALLOWED_SERVER_IP_LIST):
return
server = long_ip(ip)
# print 'server', server, dotted_ip(server), ip
for disallowed in settings.DISALLOWED_SERVER_IP_LIST:
disallowed = disallowed.strip()
if disallowed == '' or disallowed.startswith('#'):
continue
mask = bit_mask(32)
if '/' in disallowed:
disallowed, bits = disallowed.split('/', 1)
mask = slash_mask(int(bits))
identifier = long_ip(disallowed) & mask
masked = server & mask
if masked == identifier:
raise ValidationError(unicode(
_("Server IP address %(ip)s is disallowed.") % locals()))
示例2: convert
def convert(ctx, x):
if isinstance(x, (ctx.mpf, ctx.mpc)):
return x
if isinstance(x, ctx._constant):
return +x
if isinstance(x, complex) or hasattr(x, "_mpc_"):
re = ctx.convert(x.real)
im = ctx.convert(x.imag)
return ctx.mpc(re,im)
if isinstance(x, basestring):
v = mpi_from_str(x, ctx.prec)
return ctx.make_mpf(v)
if hasattr(x, "_mpi_"):
a, b = x._mpi_
else:
try:
a, b = x
except (TypeError, ValueError):
a = b = x
if hasattr(a, "_mpi_"):
a = a._mpi_[0]
else:
a = convert_mpf_(a, ctx.prec, round_floor)
if hasattr(b, "_mpi_"):
b = b._mpi_[1]
else:
b = convert_mpf_(b, ctx.prec, round_ceiling)
if a == fnan or b == fnan:
a = fninf
b = finf
assert mpf_le(a, b), "endpoints must be properly ordered"
return ctx.make_mpf((a, b))
示例3: cursor
def cursor(self, function, return_pages=False, **params):
"""Returns a generator for results that match a specified query.
:param function: Instance of a Twython function
(Twython.get_home_timeline, Twython.search)
:param \*\*params: Extra parameters to send with your request
(usually parameters accepted by the Twitter API endpoint)
:rtype: generator
Usage::
>>> from twython import Twython
>>> twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN,
OAUTH_TOKEN_SECRET)
>>> results = twitter.cursor(twitter.search, q='python')
>>> for result in results:
>>> print result
"""
if not hasattr(function, 'iter_mode'):
raise TwythonError('Unable to create generator for Twython \
method "%s"' % function.__name__)
while True:
content = function(**params)
if not content:
raise StopIteration
if hasattr(function, 'iter_key'):
results = content.get(function.iter_key)
else:
results = content
if return_pages:
yield results
else:
for result in results:
yield result
if function.iter_mode == 'cursor' and \
content['next_cursor_str'] == '0':
raise StopIteration
try:
if function.iter_mode == 'id':
if 'max_id' not in params:
# Add 1 to the id because since_id and
# max_id are inclusive
if hasattr(function, 'iter_metadata'):
since_id = content[function.iter_metadata].get('since_id_str')
else:
since_id = content[0]['id_str']
params['since_id'] = (int(since_id) - 1)
elif function.iter_mode == 'cursor':
params['cursor'] = content['next_cursor_str']
except (TypeError, ValueError): # pragma: no cover
raise TwythonError('Unable to generate next page of search \
results, `page` is not a number.')
示例4: getContextMenu
def getContextMenu(self, priority=QAction.NormalPriority):
''' Insert the subwidgets' contextMenus between double separators '''
contextMenu = None
if hasattr(self, 'actions'):
if hasattr(self.actions, 'contextMenu'):
contextMenu = self.actions.getContextMenu()
lastActionWasASeparator = False
menusWereInserted = False
for action in contextMenu.actions():
if menusWereInserted == True:
debug(self, "Menus were already inserted...", 5)
else:
if lastActionWasASeparator == False:
if action.isSeparator():
debug(self, "Found a separator...", 5)
lastActionWasASeparator = True
else:
debug(self, "Not a separator...", 5)
lastActionWasASeparator = False
else:
if not(action.isSeparator()):
debug(self, "Not a double separator...", 5)
lastActionWasASeparator = False
else:
debug(self, "Found a double separator...", 5)
for widget in self.getLWidgets() :
widgetMenu = widget.getContextMenu(priority)
if not(widgetMenu.isEmpty()):
debug(self, "Inserting %d entries in '%s'..." % (len(widgetMenu.actions()), widgetMenu.title()))
contextMenu.insertMenu(action, widgetMenu)
menusWereInserted = True
lastActionWasASeparator = True
return contextMenu
示例5: __new__
def __new__(cls, name, bases, attrs):
instance = super(OptionParserMeta, cls).__new__(cls, name, bases, attrs)
if not hasattr(instance, '_mixin_setup_funcs'):
instance._mixin_setup_funcs = []
if not hasattr(instance, '_mixin_process_funcs'):
instance._mixin_process_funcs = []
if not hasattr(instance, '_mixin_after_parsed_funcs'):
instance._mixin_after_parsed_funcs = []
for base in _sorted(bases + (instance,)):
func = getattr(base, '_mixin_setup', None)
if func is not None and func not in instance._mixin_setup_funcs:
instance._mixin_setup_funcs.append(func)
func = getattr(base, '_mixin_after_parsed', None)
if func is not None and func not in instance._mixin_after_parsed_funcs:
instance._mixin_after_parsed_funcs.append(func)
# Mark process_<opt> functions with the base priority for sorting
for func in dir(base):
if not func.startswith('process_'):
continue
func = getattr(base, func)
if getattr(func, '_mixin_prio_', None) is not None:
# Function already has the attribute set, don't override it
continue
func.__func__._mixin_prio_ = getattr(base, '_mixin_prio_', 1000)
return instance
示例6: _extend
def _extend(self, json, site):
self.id = json.question_id
self.creation_date = datetime.datetime.fromtimestamp(json.creation_date)
self.vote_count = self.up_vote_count - self.down_vote_count
self.timeline = StackExchangeLazySequence(TimelineEvent, None, site, json.question_timeline_url, self._up('timeline'))
self.revisions = StackExchangeLazySequence(PostRevision, None, site, 'revisions/%s' % self.id, self._up('revisions'), 'revisions')
self.comments_url = json.question_comments_url
self.comments = StackExchangeLazySequence(Comment, None, site, self.comments_url, self._up('comments'))
self.answers_url = json.question_answers_url
if hasattr(json, 'answers'):
self.answers = [Answer(x, site) for x in json.answers]
else:
self.answers = []
if hasattr(json, 'owner'):
self.owner_id = json.owner['user_id']
owner_dict = dict(json.owner)
owner_dict['id'] = self.owner_id
del owner_dict['user_id']
owner_dict['user_type'] = UserType.from_string(owner_dict['user_type'])
self.owner = User.partial(lambda self: self.site.user(self.id), site, owner_dict)
self.url = 'http://' + self.site.root_domain + '/questions/' + str(self.id)
示例7: _build_conch_options
def _build_conch_options(self):
"""Verify and construct the ssh (conch) option object
This is just a dictionary like object that options the twisted ssh implementation uses.
"""
ssh_options = options.ConchOptions()
if not hasattr(self, 'agent'):
ssh_options['noagent'] = True
else:
if 'SSH_AUTH_SOCK' in os.environ:
ssh_options['agent'] = True
else:
raise Error("No SSH Agent available ($SSH_AUTH_SOCK)")
if hasattr(self, "identities"):
for file_name in self.identities:
file_path = os.path.expanduser(file_name)
if not os.path.exists(file_path):
raise Error("Private key file %s doesn't exist" % file_name)
if not os.path.exists(file_path + ".pub"):
raise Error("Public key %s doesn't exist" % (file_name + ".pub"))
ssh_options.opt_identity(file_name)
return ssh_options
示例8: process
def process(self, formdata=None, obj=None, **kwargs):
"""
Take form, object data, and keyword arg input and have the fields
process them.
:param formdata:
Used to pass data coming from the enduser, usually `request.POST` or
equivalent.
:param obj:
If `formdata` has no data for a field, the form will try to get it
from the passed object.
:param `**kwargs`:
If neither `formdata` or `obj` contains a value for a field, the
form will assign the value of a matching keyword argument to the
field, if provided.
"""
if formdata is not None and not hasattr(formdata, 'getlist'):
if hasattr(formdata, 'getall'):
formdata = WebobInputWrapper(formdata)
else:
raise TypeError("formdata should be a multidict-type wrapper that supports the 'getlist' method")
for name, field, in self._fields.iteritems():
if obj is not None and hasattr(obj, name):
field.process(formdata, getattr(obj, name))
elif name in kwargs:
field.process(formdata, kwargs[name])
else:
field.process(formdata)
示例9: test_custom_lookup_ns_fallback
def test_custom_lookup_ns_fallback(self):
class TestElement1(etree.ElementBase):
FIND_ME = "custom"
class TestElement2(etree.ElementBase):
FIND_ME = "nsclasses"
class MyLookup(etree.CustomElementClassLookup):
def lookup(self, t, d, ns, name):
if name == 'c1':
return TestElement1
lookup = etree.ElementNamespaceClassLookup( MyLookup() )
etree.set_element_class_lookup(lookup)
ns = lookup.get_namespace("otherNS")
ns[None] = TestElement2
root = etree.XML(xml_str)
self.assertFalse(hasattr(root, 'FIND_ME'))
self.assertEqual(root[0].FIND_ME,
TestElement1.FIND_ME)
self.assertFalse(hasattr(root[0][1], 'FIND_ME'))
self.assertEqual(root[0][-1].FIND_ME,
TestElement2.FIND_ME)
示例10: _handle
def _handle(self, args):
if len(args) == 0:
self._raise_omni_error('Insufficient number of arguments - Missing command to run')
call = args[0].lower()
# disallow calling private methods
if call.startswith('_'):
return
if hasattr(self, call):
return getattr(self, call)(args[1:])
elif hasattr(self.chhandler, call):
return getattr(self.chhandler, call)(args[1:])
elif hasattr(self.amhandler, call):
# Extract the slice name arg and put it in an option
self.amhandler.opts.sliceName = self.amhandler._extractSliceArg(args)
# Try to auto-correct API version
msg = self.amhandler._correctAPIVersion(args)
if msg is None:
msg = ""
(message, val) = getattr(self.amhandler,call)(args[1:])
if message is None:
message = ""
return (msg+message, val)
else:
self._raise_omni_error('Unknown function: %s' % call)
示例11: overload
def overload(func):
"""Function decorator for defining overloaded functions."""
frame = sys._getframe(1)
locals = frame.f_locals
# See if there is a previous overload variant available. Also verify
# that the existing function really is overloaded: otherwise, replace
# the definition. The latter is actually important if we want to reload
# a library module such as genericpath with a custom one that uses
# overloading in the implementation.
if func.__name__ in locals and hasattr(locals[func.__name__], 'dispatch'):
orig_func = locals[func.__name__]
def wrapper(*args, **kwargs):
ret, ok = orig_func.dispatch(*args, **kwargs)
if ok:
return ret
return func(*args, **kwargs)
wrapper.isoverload = True
wrapper.dispatch = make_dispatcher(func, orig_func.dispatch)
wrapper.next = orig_func
wrapper.__name__ = func.__name__
if hasattr(func, '__isabstractmethod__'):
# Note that we can't reliably check that abstractmethod is
# used consistently across overload variants, so we let a
# static checker do it.
wrapper.__isabstractmethod__ = func.__isabstractmethod__
return wrapper
else:
# Return the initial overload variant.
func.isoverload = True
func.dispatch = make_dispatcher(func)
func.next = None
return func
示例12: _enterRawMode
def _enterRawMode():
global _inRawMode, _savedRawMode
if _inRawMode:
return
fd = sys.stdin.fileno()
try:
old = tty.tcgetattr(fd)
new = old[:]
except:
log.msg('not a typewriter!')
else:
# iflage
new[0] = new[0] | tty.IGNPAR
new[0] = new[0] & ~(tty.ISTRIP | tty.INLCR | tty.IGNCR | tty.ICRNL |
tty.IXON | tty.IXANY | tty.IXOFF)
if hasattr(tty, 'IUCLC'):
new[0] = new[0] & ~tty.IUCLC
# lflag
new[3] = new[3] & ~(tty.ISIG | tty.ICANON | tty.ECHO | tty.ECHO |
tty.ECHOE | tty.ECHOK | tty.ECHONL)
if hasattr(tty, 'IEXTEN'):
new[3] = new[3] & ~tty.IEXTEN
#oflag
new[1] = new[1] & ~tty.OPOST
new[6][tty.VMIN] = 1
new[6][tty.VTIME] = 0
_savedRawMode = old
tty.tcsetattr(fd, tty.TCSANOW, new)
#tty.setraw(fd)
_inRawMode = 1
示例13: destroy
def destroy(self):
self.disable()
if hasattr(self, 'wrongWaySeq'):
self.wrongWaySeq.finish()
self.wrongWaySeq = None
taskMgr.removeTasksMatching('removeIt')
taskMgr.removeTasksMatching('removeCam*')
taskMgr.removeTasksMatching('clearRaceEndPanel')
for obj in self.directObjList:
obj.destroy()
if hasattr(self, 'mapScene'):
self.mapScene.removeNode()
self.mapScene = None
self.aspect2dRoot.removeNode()
self.aspect2dRoot = None
self.raceModeRoot.removeNode()
self.raceModeRoot = None
self.render2dRoot.removeNode()
self.render2dRoot = None
self.closeButton = None
self.gag = None
self.lapLabel = None
self.timeLabels = None
self.placeLabelStr = None
self.placeLabelNum = None
self.photoFinishLabel = None
self.mapScene = None
self.race = None
return
示例14: create
def create(cls, **kwargs):
instance = cls(**kwargs)
if hasattr(instance, 'created_at'):
setattr(instance, 'created_at', datetime.datetime.utcnow())
if hasattr(instance, 'modified_at'):
setattr(instance, 'modified_at', datetime.datetime.utcnow())
return instance
示例15: highlightBlock
def highlightBlock(self, qstring):
""" Highlight a block of text.
"""
qstring = compat.unicode(qstring)
prev_data = self.previous_block_data()
if prev_data is not None:
self._lexer._epd_state_stack = prev_data.syntax_stack
elif hasattr(self._lexer, '_epd_state_stack'):
del self._lexer._epd_state_stack
index = 0
# Lex the text using Pygments
for token, text in self._lexer.get_tokens(qstring):
l = len(text)
format = self._get_format(token)
if format is not None:
self.setFormat(index, l, format)
index += l
if hasattr(self._lexer, '_epd_state_stack'):
data = BlockUserData(syntax_stack=self._lexer._epd_state_stack)
self.currentBlock().setUserData(data)
# there is a bug in pyside and it will crash unless we
# hold on to the reference a little longer
data = self.currentBlock().userData()
# Clean up for the next go-round.
del self._lexer._epd_state_stack