All Samples(106325) | Call(106325) | Derive(0) | Import(0)
hasattr(object, name) -> bool Return whether the object has an attribute with the given name. (This is done by calling getattr(object, name) and catching exceptions.)
src/i/r/ironruby-HEAD/Languages/IronPython/Samples/ClrType/clrtype.py ironruby(Download)
is_typed = clr.GetPythonType(clr_type) == t
# is_typed needs to be weakened until the generated type
# gets explicitly published as the underlying CLR type
is_typed = is_typed or (hasattr(t, "__metaclass__") and t.__metaclass__ in [ClrInterface, ClrClass])
if not is_typed:
raise Exception, "Invalid CLR type %s" % str(t)
if not var_signature:
if clr_type.IsByRef:
raise TypeError("Byref can only be used as arguments and locals")
# ArgIterator is not present in Silverlight
if hasattr(System, "ArgIterator") and t == System.ArgIterator:
def is_typed_method(self, function):
if hasattr(function, "arg_types") != hasattr(function, "return_type"):
raise TypeError("One of @accepts and @returns is missing for %s" % function.func_name)
return hasattr(function, "arg_types")
def get_typed_properties(self):
def emit_classattribs(self, typebld):
if hasattr(self, '_clrclassattribs'):
for attrib_info in self._clrclassattribs:
if isinstance(attrib_info, type):
ci = clr.GetClrType(attrib_info).GetConstructor(())
cab = CustomAttributeBuilder(ci, ())
elif isinstance(attrib_info, CustomAttributeDecorator):
def get_clr_type_name(self):
if hasattr(self, "_clrnamespace"):
return self._clrnamespace + "." + self.__name__
else:
return self.__name__
def create_type(self, typebld):
# TODO - set non-trivial ParameterAttributes, default value and custom attributes
p = method_builder.DefineParameter(i + 1, ParameterAttributes.None, arg_names[i + instance_offset])
if hasattr(function, "CustomAttributeBuilders"):
for cab in function.CustomAttributeBuilders:
method_builder.SetCustomAttribute(cab)
def emit_fields(self, typebld):
if hasattr(self, "_clrfields"):
for fldname in self._clrfields:
field_type = self._clrfields[fldname]
validate_clr_types(field_type)
typebld.DefineField(
fldname,
clr.GetClrType(field_type),
FieldAttributes.Public)
def map_fields(self, new_type):
if hasattr(self, "_clrfields"):
def emit_method(self, typebld, function_info):
function = function_info.function
if hasattr(function, "DllImportAttributeDecorator"):
dllImportAttributeDecorator = function.DllImportAttributeDecorator
name = function.func_name
dllName = dllImportAttributeDecorator.args[0]
entryName = function.func_name
else:
method_builder = self.emit_typed_stub_to_python_method(typebld, function_info)
if hasattr(function, "CustomAttributeBuilders"):
for cab in function.CustomAttributeBuilders:
method_builder.SetCustomAttribute(cab)
return method_builder
def map_pinvoke_methods(self, new_type):
pythonType = clr.GetPythonType(new_type)
for function_info in self.get_typed_methods():
function = function_info.function
if hasattr(function, "DllImportAttributeDecorator"):
def __call__(self, function):
if self.attrib_type == DllImportAttribute:
function.DllImportAttributeDecorator = self
else:
if not hasattr(function, "CustomAttributeBuilders"):
function.CustomAttributeBuilders = []
function.CustomAttributeBuilders.append(self.GetBuilder())
def propagate_attributes(old_function, new_function):
"""
Use this if you replace a function in a type with ClrInterface or ClrClass as the metaclass.
This will typically be needed if you are defining a decorator which wraps functions with
new functions, and want it to work in conjunction with clrtype
"""
if hasattr(old_function, "return_type"):
new_function.func_name = old_function.func_name
new_function.return_type = old_function.return_type
new_function.arg_types = old_function.arg_types
if hasattr(old_function, "CustomAttributeBuilders"):
new_function.CustomAttributeBuilders = old_function.CustomAttributeBuilders
if hasattr(old_function, "CustomAttributeBuilders"):
src/i/r/ironruby-HEAD/Languages/IronPython/Samples/IronTunes/avalon.py ironruby(Download)
def Walk(tree):
yield tree
if hasattr(tree, 'Children'):
for child in tree.Children:
for x in Walk(child):
yield x
elif hasattr(tree, 'Child'):
for x in Walk(tree.Child):
yield x
elif hasattr(tree, 'Content'):
def LoadNames(tree, namespace):
for node in Walk(tree):
if hasattr(node, 'Name'):
namespace[node.Name] = node
src/i/r/ironruby-HEAD/Languages/IronPython/Samples/Direct3D/framework.py ironruby(Download)
def GetFunctionName(f):
"Creates a formatted function string for display."
try:
name = f.__name__
if hasattr(f, "im_class"):
name = f.im_class.__name__ + "." + name
return name
listener = listener()
for key in self.KeyListeners.Keys:
if hasattr(listener, key):
self.KeyListeners[key].Add(getattr(listener, key))
self.Listeners[event].Remove(f)
else:
for key in self.KeyListeners.Keys:
if hasattr(listener, key):
self.KeyListeners[key].Remove(getattr(listener, key))
def __FireKeyEvent(self, seq, key):
self.Background, 1, 0)
self.Device.BeginScene()
for mesh in (x for x in self.Objects.Values if hasattr(x, "GetWorldMatrix")):
if callable(mesh.GetWorldMatrix):
try:
self.Device.Transform.World = mesh.GetWorldMatrix()
# have a Name, but it's possible we have been given a bogus object keyed to something
# other than its name). This keeps us from infinitely poping up error messages if we
# actually cannot find the offending object to remove.
if hasattr(mesh, "Name"):
name = str(mesh.Name)
if name in self.Objects:
def RemoveListenerByType(self, event, type):
for f in self.Listeners[event]:
if hasattr(f, 'im_class'):
if f.im_class == type:
self.Listeners[event].Remove(f)
def RemoveListener(self, obj):
for key in self.Listeners.Keys:
self.RemoveListenerByInstance(key, obj)
key = str(key)
if hasattr(obj, key):
if issubclass(type(obj), type) or type(obj) == ClassType:
self.RemoveListenerByType(key, obj)
else:
obj = obj()
for key in self.Listeners.Keys:
if hasattr(obj, str(key)):
function = getattr(obj, str(key))
self.AddEventListener(key, function)
def Main(self, listeners = []):
"""Runs the application, registering the list of listeners given by the
listeners parameter. Listeners can be an instance of a Listener class,
it could be a class object of a listener class (in which case an
instance will be created by calling the constructor with no params),
or it could be a list of either of those."""
if not hasattr(self, "Initialized"):
def ThreadMain(self, listeners = []):
"Starts main in a background thread."
if not hasattr(self, "Initialized"):
self.Init()
args = (listeners,)
thread.start_new_thread(self.Main, args)
src/m/a/matplotlib-HEAD/matplotlib/examples/units/basic_units.py matplotlib(Download)
def __call__(self, *args):
converted_args = []
arg_units = [self.unit]
for a in args:
if hasattr(a, 'get_unit') and not hasattr(a, 'convert_to'):
# if this arg has a unit type but no conversion ability,
# this operation is prohibited
return NotImplemented
if hasattr(a, 'convert_to'):
converted_args.append(a.get_value())
else:
converted_args.append(a)
if hasattr(a, 'get_unit'):
arg_units.append(a.get_unit())
else:
arg_units.append(None)
def __getattribute__(self, name):
if (name.startswith('__')):
return object.__getattribute__(self, name)
variable = object.__getattribute__(self, 'value')
if (hasattr(variable, name) and name not in self.__class__.__dict__):
return getattr(variable, name)
return object.__getattribute__(self, name)
def __mul__(self, rhs):
value = rhs
unit = self
if hasattr(rhs, 'get_unit'):
value = rhs.get_value()
unit = rhs.get_unit()
unit = unit_resolver('__mul__', (self, unit))
label=unit.fullname,
)
elif unit is not None:
if hasattr(unit, 'fullname'):
return units.AxisInfo(label=unit.fullname)
elif hasattr(unit, 'unit'):
return units.AxisInfo(label=unit.unit.fullname)
src/n/o/notmm-0.4.1/examples/lib/satchmo_admin/validation.py notmm(Download)
validate_base(cls, model)
# list_display
if hasattr(cls, 'list_display'):
check_isseq(cls, 'list_display', cls.list_display)
for idx, field in enumerate(cls.list_display):
if not callable(field):
if not hasattr(cls, field):
if not hasattr(model, field):
% (cls.__name__, idx, field))
# list_display_links
if hasattr(cls, 'list_display_links'):
check_isseq(cls, 'list_display_links', cls.list_display_links)
for idx, field in enumerate(cls.list_display_links):
fetch_attr(cls, model, opts, 'list_display_links[%d]' % idx, field)
if field not in cls.list_display:
raise ImproperlyConfigured("'%s.list_display_links[%d]'"
"refers to '%s' which is not defined in 'list_display'."
% (cls.__name__, idx, field))
# list_filter
if hasattr(cls, 'list_filter'):
get_field(cls, model, opts, 'list_filter[%d]' % idx, field)
# list_per_page = 100
if hasattr(cls, 'list_per_page') and not isinstance(cls.list_per_page, int):
raise ImproperlyConfigured("'%s.list_per_page' should be a integer."
% cls.__name__)
# list_editable
if hasattr(cls, 'list_editable') and cls.list_editable:
% (cls.__name__, idx, field_name))
# search_fields = ()
if hasattr(cls, 'search_fields'):
check_isseq(cls, 'search_fields', cls.search_fields)
# date_hierarchy = None
continue
get_field(cls, model, opts, 'ordering[%d]' % idx, field)
if hasattr(cls, "readonly_fields"):
check_isseq(cls, "readonly_fields", cls.readonly_fields)
for idx, field in enumerate(cls.readonly_fields):
if not callable(field):
if not hasattr(cls, field):
if not hasattr(model, field):
# inlines = []
if hasattr(cls, 'inlines'):
check_isseq(cls, 'inlines', cls.inlines)
for idx, inline in enumerate(cls.inlines):
if not issubclass(inline, BaseModelAdmin):
% (cls.__name__, attr))
# formset
if hasattr(cls, 'formset') and not issubclass(cls.formset, BaseModelFormSet):
raise ImproperlyConfigured("'%s.formset' does not inherit from "
"BaseModelFormSet." % cls.__name__)
# exclude
if hasattr(cls, 'exclude') and cls.exclude:
def validate_base(cls, model):
opts = model._meta
# raw_id_fields
if hasattr(cls, 'raw_id_fields'):
check_isseq(cls, 'raw_id_fields', cls.raw_id_fields)
for idx, field in enumerate(cls.raw_id_fields):
# form
if hasattr(cls, 'form') and not issubclass(cls.form, BaseModelForm):
raise ImproperlyConfigured("%s.form does not inherit from "
"BaseModelForm." % cls.__name__)
# filter_vertical
if hasattr(cls, 'filter_vertical'):
"a ManyToManyField." % (cls.__name__, idx))
# filter_horizontal
if hasattr(cls, 'filter_horizontal'):
check_isseq(cls, 'filter_horizontal', cls.filter_horizontal)
for idx, field in enumerate(cls.filter_horizontal):
f = get_field(cls, model, opts, 'filter_horizontal', field)
if not isinstance(f, models.ManyToManyField):
raise ImproperlyConfigured("'%s.filter_horizontal[%d]' must be "
"a ManyToManyField." % (cls.__name__, idx))
# radio_fields
if hasattr(cls, 'radio_fields'):
% (cls.__name__, field))
# prepopulated_fields
if hasattr(cls, 'prepopulated_fields'):
check_isdict(cls, 'prepopulated_fields', cls.prepopulated_fields)
for field, val in cls.prepopulated_fields.items():
f = get_field(cls, model, opts, 'prepopulated_fields', field)
src/m/a/matplotlib-HEAD/examples/units/basic_units.py matplotlib(Download)
def __call__(self, *args):
converted_args = []
arg_units = [self.unit]
for a in args:
if hasattr(a, 'get_unit') and not hasattr(a, 'convert_to'):
# if this arg has a unit type but no conversion ability,
# this operation is prohibited
return NotImplemented
if hasattr(a, 'convert_to'):
converted_args.append(a.get_value())
else:
converted_args.append(a)
if hasattr(a, 'get_unit'):
arg_units.append(a.get_unit())
else:
arg_units.append(None)
def __getattribute__(self, name):
if (name.startswith('__')):
return object.__getattribute__(self, name)
variable = object.__getattribute__(self, 'value')
if (hasattr(variable, name) and name not in self.__class__.__dict__):
return getattr(variable, name)
return object.__getattribute__(self, name)
def __mul__(self, rhs):
value = rhs
unit = self
if hasattr(rhs, 'get_unit'):
value = rhs.get_value()
unit = rhs.get_unit()
unit = unit_resolver('__mul__', (self, unit))
label=unit.fullname,
)
elif unit is not None:
if hasattr(unit, 'fullname'):
return units.AxisInfo(label=unit.fullname)
elif hasattr(unit, 'unit'):
return units.AxisInfo(label=unit.unit.fullname)
src/m/a/matplotlib-HEAD/py4science/examples/BeautifulSoup.py matplotlib(Download)
def replaceWith(self, replaceWith):
oldParent = self.parent
myIndex = self.parent.contents.index(self)
if hasattr(replaceWith, 'parent') and replaceWith.parent == self.parent:
# We're replacing this element with one of its siblings.
index = self.parent.contents.index(replaceWith)
if index and index < myIndex:
def _lastRecursiveChild(self):
"Finds the last element beneath this object to be parsed."
lastChild = self
while hasattr(lastChild, 'contents') and lastChild.contents:
lastChild = lastChild.contents[-1]
return lastChild
newChild = NavigableString(newChild)
position = min(position, len(self.contents))
if hasattr(newChild, 'parent') and newChild.parent != None:
# We're 'inserting' an element that's already one
# of this object's children.
if newChild.parent == self:
def __eq__(self, other):
"""Returns true iff this tag has the same name, the same attributes,
and the same contents (recursively) as the given tag.
NOTE: right now this will return false if two tags have the
same attributes in a different order. Should this be fixed?"""
if not hasattr(other, 'name') or not hasattr(other, 'attrs') or not hasattr(other, 'contents') or self.name != other.name or self.attrs != other.attrs or len(self) != len(other):
markupAttrMap = None
for attr, matchAgainst in self.attrs.items():
if not markupAttrMap:
if hasattr(markupAttrs, 'get'):
markupAttrMap = markupAttrs
else:
markupAttrMap = {}
if markup and not isString(markup):
markup = unicode(markup)
#Now we know that chunk is either a string, or None.
if hasattr(matchAgainst, 'match'):
# It's a regexp object.
result = markup and matchAgainst.search(markup)
elif isList(matchAgainst):
result = markup in matchAgainst
elif hasattr(matchAgainst, 'items'):
def isList(l):
"""Convenience method that works with all 2.x versions of Python
to determine whether or not something is listlike."""
return hasattr(l, '__iter__') \
or (type(l) in (types.ListType, types.TupleType))
def isString(s):
def buildTagMap(default, *args):
"""Turns a list of maps, lists, or scalars into a single map.
Used to build the SELF_CLOSING_TAGS, NESTABLE_TAGS, and
NESTING_RESET_TAGS maps out of lists and partial maps."""
built = {}
for portion in args:
if hasattr(portion, 'items'):
self.instanceSelfClosingTags = buildTagMap(None, selfClosingTags)
SGMLParser.__init__(self)
if hasattr(markup, 'read'): # It's a file-type object.
markup = markup.read()
self.markup = markup
self.markupMassage = markupMassage
def _feed(self, inDocumentEncoding=None):
# Convert the document to Unicode.
markup = self.markup
if isinstance(markup, unicode):
if not hasattr(self, 'originalEncoding'):
self.originalEncoding = None
else:
src/p/y/pyisapie-HEAD/Tags/Imported/v1-0-3/PyISAPIe/Python/Examples/Django/pyisapie.py pyisapie(Download)
def _get_request(This):
if not hasattr(This, '_request'):
This._request = datastructures.MergeDict(This.POST, This.GET)
return This._request
def _get_get(This):
if not hasattr(This, '_get'):
def _get_post(This):
if not hasattr(This, '_post'):
This._load_post_and_files()
return This._post
def _set_post(This, post):
This._post = post
def _get_cookies(This):
if not hasattr(This, '_cookies'):
def _get_files(This):
if not hasattr(This, '_files'):
This._load_post_and_files()
return This._files
def _get_meta(This):
"Lazy loader that returns This.META dictionary"
if not hasattr(This, '_meta'):
def _get_user(This):
if not hasattr(This, '_user'):
from django.models.auth import users
try:
user_id = This.session[users.SESSION_KEY]
if not user_id:
raise ValueError
src/p/y/pyisapie-HEAD/Tags/Imported/v1-0-2/PyISAPIe/Python/Examples/Django/pyisapie.py pyisapie(Download)
def _get_request(This):
if not hasattr(This, '_request'):
This._request = datastructures.MergeDict(This.POST, This.GET)
return This._request
def _get_get(This):
if not hasattr(This, '_get'):
def _get_post(This):
if not hasattr(This, '_post'):
This._load_post_and_files()
return This._post
def _set_post(This, post):
This._post = post
def _get_cookies(This):
if not hasattr(This, '_cookies'):
def _get_files(This):
if not hasattr(This, '_files'):
This._load_post_and_files()
return This._files
def _get_meta(This):
"Lazy loader that returns This.META dictionary"
if not hasattr(This, '_meta'):
def _get_user(This):
if not hasattr(This, '_user'):
from django.models.auth import users
try:
user_id = This.session[users.SESSION_KEY]
if not user_id:
raise ValueError
src/p/y/pyisapie-HEAD/Tags/Imported/v1-0-1/PyISAPIe/Python/Examples/Django/pyisapie.py pyisapie(Download)
def _get_request(This):
if not hasattr(This, '_request'):
This._request = datastructures.MergeDict(This.POST, This.GET)
return This._request
def _get_get(This):
if not hasattr(This, '_get'):
def _get_post(This):
if not hasattr(This, '_post'):
This._load_post_and_files()
return This._post
def _set_post(This, post):
This._post = post
def _get_cookies(This):
if not hasattr(This, '_cookies'):
def _get_files(This):
if not hasattr(This, '_files'):
This._load_post_and_files()
return This._files
def _get_meta(This):
"Lazy loader that returns This.META dictionary"
if not hasattr(This, '_meta'):
def _get_user(This):
if not hasattr(This, '_user'):
from django.models.auth import users
try:
user_id = This.session[users.SESSION_KEY]
if not user_id:
raise ValueError
1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 Next