201 questions
1
vote
1
answer
151
views
How to implement Python's unified attribute lookup (__getattribute__) in C++, handling descriptors and metaclasses?
I'm developing a Python interpreter from scratch in C++ as a hobby project to deepen my understanding of the language's internals.
I'm currently stuck on implementing the attribute lookup mechanism (...
2
votes
3
answers
197
views
How to correctly type-annotate a classmethod-like descriptor in python?
classonlymethod decorator/descriptor defined below is like the built-in classmethod, but you're not allowed to call the method on instances, only on the class itself.
from typing import Concatenate, ...
1
vote
1
answer
77
views
Exception thrown in python magic method is lost on the way
For a project, I want to prevent the use of certain methods in an overriding class.
As this happens rather frequently, I am using a metaclass to block many methods at once (how and why is not within ...
1
vote
0
answers
72
views
Can I override type of an existing attribute by `__getattribute__` method?
I wrote a simple code where I override the __getattribute__ method so that it always returns an empty string. But Pyright doesn't understand this and complains "int" is not assignable to &...
1
vote
1
answer
129
views
How to create different type for class variable and instance variable
I want to explain to Pyright that my variables in class and instance have different types.
I managed to overload __get__ method to achieve this, but now Pyright complains about initialization of ...
2
votes
1
answer
75
views
How to pass any object as a classmethod's first argument - circumvent injection of class argument
Passing a class, or a totally different object, as the first argument to method is easy:
class Foo:
def method(self): ...
Foo.method(object()) # pass anything to self
I wonder, is this possible ...
1
vote
1
answer
85
views
How to check if an object is a method_descriptor
Given an object, how can I make a check if it is a method_descriptor?
is_method_descriptor = isinstance(obj, method_descriptor) # does not work
The problem: method_descriptor is a builtin but not an ...
1
vote
1
answer
91
views
Python descriptors on Readonly attributes
I want to refactor a big part of my code into a generic descriptor for read only attribute access. The following is an example of property based implementation
class A:
def __init__(self, n):
...
1
vote
1
answer
79
views
Dynamic read-only attributes in python instances
EDIT This code contains several bugs, see jsbueno's answer below for a correct version
I would like to create read-only attributes that dynamically retrieve values from an internal dictionary. I have ...
1
vote
0
answers
170
views
Descriptor type hints
I'm trying to use type hints in my code but I simply don't understand how the concept applies to a Python descriptor. The only relevant info I could find on the matter was this 6+ year old post but I ...
2
votes
3
answers
197
views
Properties vs. generic setter/getter and descriptor
I can't seem to find a definitive answer on the matter and I guess the reason is because it depends on the situation.
a, b and c (and d, e, f... as only 3 attributes are listed in this example for ...
0
votes
0
answers
16
views
Descriptor as decorator with variable arguments [duplicate]
I want to create a @property like feature with serialization capabilities. It would take some arguments.
I have created a descriptor like so:
class CustomMethod:
def __init__(self, serialize: bool ...
0
votes
0
answers
47
views
How to track access to class variables in a custom ORM using Python descriptors?
I'm building my own ORM in Python and ran into an issue. I want to track the access to class variables in order to know which ForeignKey is being used in each part of my code.
class IQuery(ABC):
&...
0
votes
2
answers
92
views
Descriptor in DataClass
Here is descriptor class:
#descriptor
class Validator:
def __set_name__(self,owner,name):
self.private_name = '_' + name
def __set__(self,obj,value):
self.validate(value)
...
1
vote
1
answer
60
views
Decorate instance methods with decorator class that replaces method with class instance
I would like to be able to decorate instance methods with a class Step such that the methods are replaced by a Step object. At the same time, I'd like to have the option be able to instantiate a step ...
1
vote
1
answer
189
views
Python annotate adding class members in __get__
I want to create a decorator that adds a member to the decorated class
that is instance of outer class.
In this case, decorator memberclass adds attribute self to the instance of class y that is of ...
2
votes
0
answers
237
views
Type hinting a python descriptor implementing read-only instance attributes after initialisation
I have a couple of data structure classes that are intended to have public read-only attributes. I cannot use dataclasses or namedtuples as I need the ability to define args, kwargs in the child ...
0
votes
1
answer
167
views
Is there a way to set an instance variable without calling a descriptors __set__ method?
I have made a custom descriptor which I've assigned to a value in my class. However I would like to set the instance variable initially without using the descriptors __set__ method.
class Descriptor:
...
-1
votes
1
answer
80
views
Is there a better way of detecting when attributes are changed than using decorators?
I have been refactoring a text class meant for blitting text to the screen.
I recently learned about the @property decorator and thought using it in this class would help.
Here is a stripped down ...
1
vote
2
answers
139
views
Decorator with argument trying to access the self variable doesn't seem to extract self, but self.x instead
I have the following code involving a decorator decorating a property getter into a property-like object that reimplements mutation dunders to also invoke a specified function attribute fetched from ...
3
votes
3
answers
127
views
Accessing attributes of a Python Descriptor
Not sure if this is feasible or not. The implementation/example below is dummy, FYI.
I have a Python class, Person. Each person has a public first name and a public last name attribute with ...
0
votes
1
answer
55
views
Getting access to a protected member warning shown by pycharm in descriptor get method
I was trying to play around with Python descriptors and Pycharm IDE seems to be complaining
Am I using descriptors incorrectly? Or is this expected?
Complete code:
class Age:
def __set__(self, ...
1
vote
1
answer
63
views
How to get a variable name from within the function it call for assignment? [duplicate]
I need to get the name of a variable from within a function it call during assignment. For example if we take the code:
class CharField:
def __init__(self):
self.field_name = ???
...
1
vote
1
answer
107
views
Is it possible to invoke the descriptor deleter from a class?
I have a data-descriptor whose purpose is to read and write data from file, and delete this file :
import os
class ValueFromFile:
...
def __set_name__(self, owner, name):
self.name =...
0
votes
1
answer
106
views
Mechanics of python attribute setting on class types, for use in descriptor setters
Recently, with the change of the @classmethod decorator no longer being able to wrap the @property decorator (Python >= 3.11), there has been significant interest in how to create a @classproperty ...
0
votes
1
answer
93
views
What should be a type annotation for dataclass descriptor fields?
I'm working on a class for which user should be able to set its fields in the most convenient way, which includes assigning strings to any of the fields. Values assigned by the user should be ...
0
votes
0
answers
55
views
Why does this python decorator refuse to set the setter?
This is my code:
class Property:
def __init__(self, fget, fset):
self.fget = fget
self.fset = fset
def __get__(self, obj, objtype=None):
return self.fget(obj)
...
0
votes
1
answer
67
views
Same attribute name of an object in python descriptor and __init__ function [duplicate]
I was reading about python descriptors and how to use them. I came across an example from the python official doc,
import logging
logging.basicConfig(level=logging.INFO)
class LoggedAgeAccess:
...
-1
votes
1
answer
88
views
Automatic updates for class attributes when modifying a list-like attribute in Python using __set__ and __setitem__
I have a class with an attribute ax_mask. The attribute is list like. When I change the whole attribute or just an element of it, I need some other attribute (window) in the class to be updated (i.e. ...
2
votes
1
answer
117
views
Why is __get__() specified to have an optional third argument?
The Descriptor HowTo Guide (Descriptor protocol) specifies that __get__() must be callable with 2 and 3 arguments:
descr.__get__(self, obj, type=None) -> value
Why has it been defined like this? ...
0
votes
0
answers
43
views
Generic XML message parsing
I have a number of XML message types with an elaborate header and sequence structure, but separate business message types. I'm trying convert these to objects in Python, and so far my bottom-level ...
6
votes
2
answers
580
views
Python dunder methods wrapped as property
I stumbled upon this code that I found weird as it seems to violate the fact that python builtins call dunder methods directly from the class of the object. Using __call__ as an example, if we define ...
4
votes
1
answer
114
views
Let a passed function object be called as a method
EDIT: I extended the example to show the more complex case that I was talking about before. Thanks for the feedback in the comments.
Some more context:
I am mostly interested in this on a theoretical ...
2
votes
1
answer
185
views
Why setting __set__ function for method descriptor does not make it data-descriptor?
I've started reading about descriptors in Python and created small test to see whether the order of attribute access is same as it is described. As I understand when attribute of object is accessed it ...
3
votes
2
answers
727
views
Using a cached property on a named tuple
from typing import NamedTuple
from functools import cached_property
class Rectangle(NamedTuple):
x: int
y: int
@cached_property
def area(self):
return self.x * self.y
I ...
1
vote
4
answers
727
views
Python class attribute access fails if attribute has no value [duplicate]
Earlier today i stumbled upon a behaviour with python classes which i could not fully comprehend.
If we take this piece of code:
class A:
a: str
When I test out the attribute access for a like so ...
3
votes
1
answer
133
views
Why does property override object.__getattribute__?
I noticed that contrary to the classmethod and staticmethod decorators, the property decorator overrides the object.__getattribute__ method:
>>> list(vars(classmethod))
['__new__', '__repr__',...
1
vote
1
answer
169
views
Descriptor Protocol with custom __str__() method in Python?
UPDATED Question: In Python, can I create a custom data structure that is a dict, but which I get and set as a set, and for which I can create a custom __str__ representation?
I want a class attribute ...
2
votes
3
answers
188
views
Descriptor's __set__ not invoked
I have a innerclass decorator/descriptor that is supposed to pass the outer instance to the inner callable as the first argument:
from functools import partial
class innerclass:
def __init__(self, ...
50
votes
3
answers
24k
views
Class properties in Python 3.11+
In Python 3.9, we gained the ability to chain @classmethod and @property to sensibly create class properties.
class Foo:
@property
def instance_property(self):
return "A regular property&...
1
vote
2
answers
131
views
Keeping multiple dictionaries in sync when one is the super set of the rest
I want to have a class with dictionaries that contain nodes, but nodes can be of several sorts: points, vertices,... (and possible others)
I want to efficiently loop and access over either one of ...
3
votes
1
answer
872
views
How to type hint python magic __get__ method
Suppose we have the following classes:
class Foo:
def __init__(self, method):
self.method = method
def __get__(self, instance, owner):
if instance is None:
return self
...
0
votes
1
answer
113
views
Why cls.__getattribute__ returns a function instead of a bound method whereas cls.__call__ returns a bound method
Suppose cls is a class in python. cls.__getattribute__ returns the __getattribute__ function defined on object, but it doesn't bind cls to this function. According to the descriptor protocol, cls is ...
2
votes
1
answer
189
views
Getting the base class in a descriptor called via super()
I have a following (simplified of course) descriptor:
class d:
def __init__(self, method):
self.method = method
def __get__(self, instance, owner=None):
print(instance, owner, ...
5
votes
3
answers
190
views
Descriptors in python for implementing perl's tie scalar operation
I need some help with descriptors in python. I wrote an automatic translator from perl to python (Pythonizer) and I'm trying to implement tied scalars, which is basically an object that acts as a ...
0
votes
2
answers
56
views
Does function know about the class before binding
Is there a way to access a class (where function is defined as a method) before there is an instance of that class?
class MyClass:
def method(self):
print("Calling me")
m1 = ...
0
votes
0
answers
49
views
Why does function descriptor create new bound method each time
Could you explain why new bound method is created each time when trying to access same method of the same class instance?
class MyClass:
def my_method(self):
print(f"Called bounded to ...
0
votes
1
answer
521
views
Set property on a function object
Is it possible to assign property on a function object the similar way we assign it on class instances. My desired behaviour is like this
def prop():
print("I am a property")
def ...
0
votes
2
answers
335
views
Why does super().__dict__ raise an AttributeError?
Why is this raising an AttributeError?
class A:
def f(self):
print(super().__dict__)
A().f() # raises AttributeError: 'super' object has no attribute '__dict__'
1
vote
2
answers
196
views
How do I tell pylint about a descriptor providing access to iterables, subscriptables?
I have a decorator that I can use to mark a read-only class property:
class class_ro_property(property):
def __init__(self, getter:Callable):
self._getter = getter
def __get__(self, _,...