descriptor

Neat way to get descriptor object

安稳与你 提交于 2019-12-09 16:37:56
问题 In Python 3 class A(object): attr = SomeDescriptor() ... def somewhere(self): # need to check is type of self.attr is SomeDescriptor() desc = self.__class__.__dict__[attr_name] return isinstance(desc, SomeDescriptor) Is there better way to do it? I don't like this self.__class__.__dict__ stuff 回答1: A.attr causes Python to call SomeDescriptor().__get__(None, A) so if you have SomeDescriptor.__get__ return self when inst is None , then A.attr will return the descriptor: class SomeDescriptor():

Use a Descriptor (EDIT: Not a single decorator) for multiple attributes?

爷,独闯天下 提交于 2019-12-08 11:24:35
问题 Python 2.5.4. Fairly new to Python, brand new to decorators as of last night. If I have a class with multiple boolean attributes: class Foo(object): _bool1 = True _bool2 = True _bool3 = True #et cetera def __init__(): self._bool1 = True self._bool2 = False self._bool3 = True #et cetera Is there a way to use a single decorator to check that any setting of any of the boolean attributes must be a boolean, and to return the boolean value for any requested one of these variables? In other words,

Python descriptors with old-style classes

拈花ヽ惹草 提交于 2019-12-07 03:52:30
问题 I tried to google something about it. Why do non-data descriptors work with old-style classes? Docs say that they should not: "Note that descriptors are only invoked for new style objects or classes (ones that subclass object() or type()).". class Descriptor(object): def __init__(self): self.x = 1 def __get__(self, obj, cls=None): return self.x class A: x = Descriptor() a = A() a.x >>> 1 Thanks. 回答1: You are right to question the documentation. I've tried looking through CPython sources to

Nesting descriptors/decorators in python

不羁的心 提交于 2019-12-07 03:13:37
问题 I'm having a hard time understanding what happens when I try to nest descriptors/decorators. I'm using python 2.7. For example, let's take the following simplified versions of property and classmethod : class MyProperty(object): def __init__(self, fget): self.fget = fget def __get__(self, obj, objtype=None): print 'IN MyProperty.__get__' return self.fget(obj) class MyClassMethod(object): def __init__(self, f): self.f = f def __get__(self, obj, objtype=None): print 'IN MyClassMethod.__get__'

How is __slots__ implemented in Python?

风流意气都作罢 提交于 2019-12-06 20:16:28
问题 How is __slots__ implemented in Python? Is this exposed in the C interface? How do I get __slots__ behaviour when defining a Python class in C via PyTypeObject? 回答1: When creating Python classes, they by default have a __dict__ and you can set any attribute on them. The point of slots is to not create a __dict__ to save space. In the C interface it's the other way around, an extension class has by default no __dict__ , and you would instead explicitly have to add one and add getattr/setattr

The proper way of completely overriding attribute access in Python?

房东的猫 提交于 2019-12-06 13:03:38
问题 This naive class attempts to mimic the attribute access of basic python objects. dict and cls explicitly stores the attributes and the class. The effect is that accessing .x of an instance will return dict[x] , or if that fails, cls.x . Just like normal objects. class Instance(object): __slots__ = ["dict", "cls"] def __getattribute__(self, key): try: return self.dict[key] except KeyError: return getattr(self.cls, key) def __setattr__(self, key, value): if key == "__class__": self.cls = value

Using descriptors in unhashable classes - python

纵饮孤独 提交于 2019-12-06 03:17:44
问题 A common design pattern when using python descriptors is to have the descriptor keep a dictionary of instances using that descriptor. For example, suppose I want to make an attribute that counts the number of times it's accessed: class CountingAttribute(object): def __init__(self): self.count = 0 self.value = None class MyDescriptor(object): def __init__(self): self.instances = {} #instance -> CountingAttribute def __get__(self, inst, cls): if inst in self.instances: ca = self.instances[inst]

bash: how to redirect stdin/stderr then later revert fd's?

北慕城南 提交于 2019-12-05 22:55:45
问题 I want a script to redirect stdin and stderr to a file, do a bunch of stuff, then undo those redirections and take action on the file contents. I'm trying: function redirect(){ exec 3>&1 exec 4>&2 exec 1>outfile 2>&1 } function undirect(){ exec 1>&3 exec 2>&4 } echo first redirect echo something cat kjkk undirect if some_predicate outfile; then echo ERROR; fi Which seems to do what I want, but it seems rather complex. Is there a cleaner/clearer way to do this? 回答1: If you really need to

How does Python bypass normal attribute lookup to find `__dict__`?

徘徊边缘 提交于 2019-12-05 08:14:42
问题 I understand that __dict__ in obj.__dict__ is a descriptor attribute of type(obj) , so the lookup for obj.__dict__ is type(obj).__dict__['__dict__'].__get__(obj) . From https://stackoverflow.com/a/46576009 It's tempting to say that __dict__ has to be a descriptor because implementing it as a __dict__ entry would require you to find the __dict__ before you can find the __dict__ , but Python already bypasses normal attribute lookup to find __dict__ when looking up other attributes , so that's

Python descriptors with old-style classes

感情迁移 提交于 2019-12-05 08:00:21
I tried to google something about it. Why do non-data descriptors work with old-style classes? Docs say that they should not: " Note that descriptors are only invoked for new style objects or classes (ones that subclass object() or type() ). ". class Descriptor(object): def __init__(self): self.x = 1 def __get__(self, obj, cls=None): return self.x class A: x = Descriptor() a = A() a.x >>> 1 Thanks. You are right to question the documentation. I've tried looking through CPython sources to find an explanation, but be warned: I'm no expert. From my understanding, attribute lookup and descriptor _