我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用inspect.getattr_static()。
def setupConfigOptions(cls, installDirectoryHelp="", **kwargs): super().setupConfigOptions(**kwargs) # statusUpdate("Setting up config options for", cls, cls.target) cls.sourceDir = cls.addPathOption("source-directory", metavar="DIR", default=cls.defaultSourceDir, help="Override default source directory for " + cls.projectName) cls.buildDir = cls.addPathOption("build-directory", metavar="DIR", default=cls.defaultBuildDir, help="Override default source directory for " + cls.projectName) if not installDirectoryHelp: installDirectoryHelp = "Override default install directory for " + cls.projectName cls.installDir = cls.addPathOption("install-directory", metavar="DIR", help=installDirectoryHelp, default=cls.defaultInstallDir) if "repository" in cls.__dict__: cls.gitRevision = cls.addConfigOption("git-revision", kind=str, help="The git revision to checkout prior to" " building. Useful if HEAD is broken for one project but you still" " want to update the other projects.", metavar="REVISION") cls.repository = cls.addConfigOption("repository", kind=str, help="The URL of the git repository", default=cls.repository, metavar="REPOSITORY") if inspect.getattr_static(cls, "generate_cmakelists") is None: cls.generate_cmakelists = cls.addBoolOption("generate-cmakelists", help="Generate a CMakeLists.txt that just calls cheribuild. " "Useful for IDEs that only support CMake")
def get_func_in_mro(obj: Any, code: CodeType) -> Optional[Callable]: """Attempt to find a function in a side-effect free way. This looks in obj's mro manually and does not invoke any descriptors. """ # FunctionType is incompatible with Callable # https://github.com/python/typeshed/issues/1378 val = inspect.getattr_static(obj, code.co_name, None) if val is None: return None if isinstance(val, (classmethod, staticmethod)): cand = cast(Callable, val.__func__) elif isinstance(val, property) and (val.fset is None) and (val.fdel is None): cand = cast(Callable, val.fget) else: cand = cast(Callable, val) return _has_code(cand, code)
def test_metaclass(self): class meta(type): attr = 'foo' class Thing(object, metaclass=meta): pass self.assertEqual(inspect.getattr_static(Thing, 'attr'), 'foo') class sub(meta): pass class OtherThing(object, metaclass=sub): x = 3 self.assertEqual(inspect.getattr_static(OtherThing, 'attr'), 'foo') class OtherOtherThing(OtherThing): pass # this test is odd, but it was added as it exposed a bug self.assertEqual(inspect.getattr_static(OtherOtherThing, 'x'), 3)
def test_descriptor(self): class descriptor(object): def __get__(self, instance, owner): return 3 class Foo(object): d = descriptor() foo = Foo() # for a non data descriptor we return the instance attribute foo.__dict__['d'] = 1 self.assertEqual(inspect.getattr_static(foo, 'd'), 1) # if the descriptor is a data-desciptor we should return the # descriptor descriptor.__set__ = lambda s, i, v: None self.assertEqual(inspect.getattr_static(foo, 'd'), Foo.__dict__['d'])
def test_metaclass_with_metaclass_with_dict_as_property(self): class MetaMeta(type): @property def __dict__(self): self.executed = True return dict(spam=42) class Meta(type, metaclass=MetaMeta): executed = False class Thing(metaclass=Meta): pass with self.assertRaises(AttributeError): inspect.getattr_static(Thing, "spam") self.assertFalse(Thing.executed)
def __get__(self, obj, cls): name = self.method.__name__ getattr_static = inspect.getattr_static if obj is not None: # look up the attribute, but skip cls dummy = type(cls.__name__, cls.__bases__, {}) attr = getattr_static(dummy(), name, None) getter = getattr_static(attr, '__get__', None) # try data descriptors if (getter and getattr_static(attr, '__set__', False)): return getter(attr, obj, cls) # try the instance try: instance_dict = object.__getattribute__(obj, "__dict__") except AttributeError: pass else: try: return dict.__getitem__(instance_dict, name) except KeyError: pass # try non-data descriptors if getter is not None: return getter(attr, obj, cls) raise AttributeError(name) else: descr = vars(self)['descr'] return descr.__get__(obj, cls) ################################################# # tests
def setupConfigOptions(cls, **kwargs): super().setupConfigOptions(**kwargs) cls.useMxgot = cls.addBoolOption("use-mxgot", help="Compile without -mxgot flag (should not be needed when using lld)") cls.linker = cls.addConfigOption("linker", default=cls.defaultLinker, help="The linker to use (`lld` or `bfd`) (lld is better but may" " not work for some projects!)") cls.debugInfo = cls.addBoolOption("debug-info", help="build with debug info", default=True) cls.optimizationFlags = cls.addConfigOption("optimization-flags", kind=list, metavar="OPTIONS", default=cls.defaultOptimizationLevel) # TODO: check if LLD supports it and if yes default to true? cls.newCapRelocs = cls.addBoolOption("new-cap-relocs", help="Use the new __cap_relocs processing in LLD", default=False) if inspect.getattr_static(cls, "crossCompileTarget") is None: cls.crossCompileTarget = cls.addConfigOption("target", help="The target to build for (`cheri` or `mips` or `native`)", default=defaultTarget, choices=["cheri", "mips", "native"], kind=CrossCompileTarget)
def get_attribute_name(self, instance): """ Finds the name of the attribute. :param instance: Node instance the attribute name is being looked for. :return: """ for attr in dir(instance): if inspect.getattr_static(instance, attr) is self: self.attrib_name = attr
def find_attribute_name(self, klass): """ It finds the name of the descriptor as it is defined in the paret class. :param type klass: Parent class """ # Loop through each member of the class and get it's static attribute. # This is necessary since descriptor are meant to override the default # behaviour of getattr(..) # If this instance is found get it's name. for member_name in dir(klass): member = inspect.getattr_static(klass, member_name) if member is self: self.attribute_name = member_name
def __initialize_descriptors(self): """Initializes the DescriptorInstance instances in this object.""" # I'm not sure whether this function has any effect. Descriptors are initialized when they are first requested # anyways. I probably had a reason why some descriptors had to be initialized during initialization back when I # made this function. - Aaron klass = type(self) for member_name in dir(klass): member = inspect.getattr_static(klass, member_name) if isinstance(member, DescriptorStatic): getattr(self, member_name)
def triggers(cls): """Property returning all statically declared triggers.""" tl = {} for member_name in dir(cls): member = inspect.getattr_static(cls, member_name) if isinstance(member, TriggerBase): tl[member_name] = member return tl
def ports(cls) -> dict: """Property returning all statically declared ports.""" ps = {} for member_name in dir(cls): member = inspect.getattr_static(cls, member_name) if isinstance(member, PortDescriptorBase): ps[member_name] = member return ps
def from_callable(cls, func: Callable) -> 'FunctionKind': if '.' not in func.__qualname__: return FunctionKind.MODULE func_or_desc = get_name_in_module(func.__module__, func.__qualname__, inspect.getattr_static) if isinstance(func_or_desc, classmethod): return FunctionKind.CLASS elif isinstance(func_or_desc, staticmethod): return FunctionKind.STATIC elif isinstance(func_or_desc, property): return FunctionKind.PROPERTY return FunctionKind.INSTANCE
def test_basic(self): class Thing(object): x = object() thing = Thing() self.assertEqual(inspect.getattr_static(thing, 'x'), Thing.x) self.assertEqual(inspect.getattr_static(thing, 'x', None), Thing.x) with self.assertRaises(AttributeError): inspect.getattr_static(thing, 'y') self.assertEqual(inspect.getattr_static(thing, 'y', 3), 3)
def test_inherited(self): class Thing(object): x = object() class OtherThing(Thing): pass something = OtherThing() self.assertEqual(inspect.getattr_static(something, 'x'), Thing.x)
def test_instance_attr(self): class Thing(object): x = 2 def __init__(self, x): self.x = x thing = Thing(3) self.assertEqual(inspect.getattr_static(thing, 'x'), 3) del thing.x self.assertEqual(inspect.getattr_static(thing, 'x'), 2)
def test_property(self): class Thing(object): @property def x(self): raise AttributeError("I'm pretending not to exist") thing = Thing() self.assertEqual(inspect.getattr_static(thing, 'x'), Thing.x)
def test_descriptor_raises_AttributeError(self): class descriptor(object): def __get__(*_): raise AttributeError("I'm pretending not to exist") desc = descriptor() class Thing(object): x = desc thing = Thing() self.assertEqual(inspect.getattr_static(thing, 'x'), desc)
def test_inherited_classattribute(self): class Thing(object): x = object() class OtherThing(Thing): pass self.assertEqual(inspect.getattr_static(OtherThing, 'x'), Thing.x)
def test_slots(self): class Thing(object): y = 'bar' __slots__ = ['x'] def __init__(self): self.x = 'foo' thing = Thing() self.assertEqual(inspect.getattr_static(thing, 'x'), Thing.x) self.assertEqual(inspect.getattr_static(thing, 'y'), 'bar') del thing.x self.assertEqual(inspect.getattr_static(thing, 'x'), Thing.x)
def test_no_dict_no_slots(self): self.assertEqual(inspect.getattr_static(1, 'foo', None), None) self.assertNotEqual(inspect.getattr_static('foo', 'lower'), None)
def test_no_dict_no_slots_instance_member(self): # returns descriptor with open(__file__) as handle: self.assertEqual(inspect.getattr_static(handle, 'name'), type(handle).name)
def test_metaclass_with_descriptor(self): class descriptor(object): def __get__(self, instance, owner): return 3 class meta(type): d = descriptor() class Thing(object, metaclass=meta): pass self.assertEqual(inspect.getattr_static(Thing, 'd'), meta.__dict__['d'])
def test_class_as_property(self): class Base(object): foo = 3 class Something(Base): executed = False @property def __class__(self): self.executed = True return object instance = Something() self.assertEqual(inspect.getattr_static(instance, 'foo'), 3) self.assertFalse(instance.executed) self.assertEqual(inspect.getattr_static(Something, 'foo'), 3)
def test_mro_as_property(self): class Meta(type): @property def __mro__(self): return (object,) class Base(object): foo = 3 class Something(Base, metaclass=Meta): pass self.assertEqual(inspect.getattr_static(Something(), 'foo'), 3) self.assertEqual(inspect.getattr_static(Something, 'foo'), 3)
def test_dict_as_property(self): test = self test.called = False class Foo(dict): a = 3 @property def __dict__(self): test.called = True return {} foo = Foo() foo.a = 4 self.assertEqual(inspect.getattr_static(foo, 'a'), 3) self.assertFalse(test.called)
def test_metaclass_dict_as_property(self): class Meta(type): @property def __dict__(self): self.executed = True class Thing(metaclass=Meta): executed = False def __init__(self): self.spam = 42 instance = Thing() self.assertEqual(inspect.getattr_static(instance, "spam"), 42) self.assertFalse(Thing.executed)
def test_module(self): sentinel = object() self.assertIsNot(inspect.getattr_static(sys, "version", sentinel), sentinel)