descriptor

Nesting descriptors/decorators in python

前提是你 提交于 2019-12-05 07:32:17
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__' def f(*args, **kwargs): return self.f(objtype, *args, **kwargs) return f Trying to nest them: class A

Why does declaring a descriptor class in the __init__ function break the descriptor functionality?

╄→гoц情女王★ 提交于 2019-12-05 04:57:34
In class B below I wanted the __set__ function in class A to be called whenever you assign a value to B().a . Instead, setting a value to B().a overwrites B().a with the value. Class C assigning to C().a works correctly, but I wanted to have a separate instance of A for each user class, i.e. I don't want changing 'a' in one instance of C() to change 'a' in all other instances. I wrote a couple of tests to help illustrate the problem. Can you help me define a class that will pass both test1 and test2? class A(object): def __set__(self, instance, value): print "__set__ called: ", value class B

How is __slots__ implemented in Python?

别等时光非礼了梦想. 提交于 2019-12-05 00:36:23
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 ? 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 support to handle it (although luckily there are methods for this already, PyObject_GenericGetAttr and

The proper way of completely overriding attribute access in Python?

时光总嘲笑我的痴心妄想 提交于 2019-12-04 19:29:39
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 else: self.dict[key] = value But it's nowhere near as simple as that. One obvious issue is the complete

Using descriptors in unhashable classes - python

大憨熊 提交于 2019-12-04 08:59:39
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] else: ca = CountingAttribute() self.instances[inst] = ca ca.count += 1 return ca class Foo(object): x

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

断了今生、忘了曾经 提交于 2019-12-04 05:11:14
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? If you really need to switch it back and forth, without knowing beforehand what will go where and when, that's pretty much the way to

Creating dynamic docstrings in Python descriptor

淺唱寂寞╮ 提交于 2019-12-04 03:47:29
I am trying to generate some class definitions dynamically (for wrapping a C++ extension). The following descriptor works fine except when I try to access the docstring for a field using help(), it gives default documentation for the descriptor rather than the field it self. However when I do help(classname), it retrieves the docstring passed to the descriptor: class FieldDescriptor(object): def __init__(self, name, doc='No documentation available.'): self.name = name self.__doc__ = doc def __get__(self, obj, dtype=None): if obj is None and dtype is not None: print 'Doc is:', self.__doc__

Can a method be used as either a staticmethod or instance method?

女生的网名这么多〃 提交于 2019-12-04 03:38:03
问题 I'd like to be able to do this: class A(object): @staticandinstancemethod def B(self=None, x, y): print self is None and "static" or "instance" A.B(1,2) A().B(1,2) This seems like a problem that should have a simple solution, but I can't think of or find one. 回答1: It is possible, but please don't. I couldn't help but implement it though: class staticandinstancemethod(object): def __init__(self, f): self.f = f def __get__(self, obj, klass=None): def newfunc(*args, **kw): return self.f(obj,

Neat way to get descriptor object

人走茶凉 提交于 2019-12-04 03:37:59
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 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(): def __get__(self, inst, instcls): if inst is None: # instance attribute accessed on class, return self

Programmatically generate methods for a class

孤街醉人 提交于 2019-12-04 02:34:27
I have about 20 methods to redirect to a wrapper method that takes the original method, and the rest of the arguments: class my_socket(parent): def _in(self, method, *args, **kwargs): # do funky stuff def recv(self, *args, **kwargs): return self._in(super().recv, *args, **kwargs) def recv_into(self, *args, **kwargs): return self._in(super().recv_into, *args, **kwargs) # and so on... How can I add more of these methods programmatically? This is about as far as I get before everything starts to look wrong: for method in 'recv', 'recvfrom', 'recvfrom_into', 'recv_into', ...: setattr(my_socket,