Skip to main content

python property class namespace confusion

I am confused about use of property class with regard to references to the fset/fget/fdel functions and in which namespaces they live. The behavior is different depending on whether I use property as a decorator or a helper function. Why do duplicate vars in class and instance namespaces impact one example but not the other?

When using property as a decorator shown here I must hide the var name in __dict__ with a leading underscore to prevent preempting the property functions. If not I'll see a recursion loop.

class setget():
    """Play with setters and getters"""
    @property
    def x(self):
        print('getting x')
        return self._x
    @x.setter
    def x(self, x):
        print('setting x')
        self._x = x
    @x.deleter
    def x(self):
        print('deleting x')
        del self._x

and I can see _x as an instance property and x as a class property:

>>> sg = setget()
>>> sg.x = 1
setting x
>>> sg.__dict__
{'_x': 1}
pprint(setget.__dict__)
mappingproxy({'__dict__': <attribute '__dict__' of 'setget' objects>,
              '__doc__': 'Play with setters and getters',
              '__module__': '__main__',
              '__weakref__': <attribute '__weakref__' of 'setget' objects>,
              'x': <property object at 0x000001BF3A0C37C8>})
>>> 

Here's an example of recursion if the instance var name underscore is omitted. (code not shown here) This makes sense to me because instance property x does not exist and so we look further to class properties.

>>> sg = setget()
>>> sg.x = 1
setting x
setting x
setting x
setting x
...

However if I use property as a helper function as described in one of the answers here: python class attributes vs instance attributes the name hiding underscore is not needed and there is no conflict.

Copy of the example code:

class PropertyHelperDemo:
    '''Demonstrates a property definition helper function'''
    def prop_helper(k: str, doc: str):
        print(f'Creating property instance {k}')
        def _get(self):
            print(f'getting {k}')
            return self.__dict__.__getitem__(k) # might use '_'+k, etc.
        def _set(self, v):
            print(f'setting {k}')
            self.__dict__.__setitem__(k, v)
        def _del(self):
            print(f'deleting {k}')
            self.__dict__.__delitem__(k)
        return property(_get, _set, _del, doc)

    X: float = prop_helper('X', doc="X is the best!")
    Y: float = prop_helper('Y', doc="Y do you ask?")
    Z: float = prop_helper('Z', doc="Z plane!")
    # etc...

    def __init__(self, X: float, Y: float, Z: float):
        #super(PropertyHelperDemo, self).__init__()  # not sure why this was here
        (self.X, self.Y, self.Z) = (X, Y, Z)

    # for read-only properties, the built-in technique remains sleek enough already
    @property
    def Total(self) -> float:
        return self.X + self.Y + self.Z

And here I verify that the property fset function is being executed on subsequent calls.

>>> p = PropertyHelperDemo(1, 2, 3)
setting X
setting Y
setting Z
>>> p.X = 11
setting X
>>> p.X = 111
setting X
>>> p.__dict__
{'X': 111, 'Y': 2, 'Z': 3}
>>> pprint(PropertyHelperDemo.__dict__)
mappingproxy({'Total': <property object at 0x000002333A093F98>,
              'X': <property object at 0x000002333A088EF8>,
              'Y': <property object at 0x000002333A093408>,
              'Z': <property object at 0x000002333A093D18>,
              '__annotations__': {'X': <class 'float'>,
                                  'Y': <class 'float'>,
                                  'Z': <class 'float'>},
              '__dict__': <attribute '__dict__' of 'PropertyHelperDemo' objects>,
              '__doc__': 'Demonstrates a property definition helper function',
              '__init__': <function PropertyHelperDemo.__init__ at 0x000002333A0B3AF8>,
              '__module__': '__main__',
              '__weakref__': <attribute '__weakref__' of 'PropertyHelperDemo' objects>,
              'prop_helper': <function PropertyHelperDemo.prop_helper at 0x000002333A052F78>})
>>> 

I can see the class and instance properties with overlapping names X, Y, Z, in the two namespaces. It is my understanding that the namespace search order begins with local variables so I don't understand why the property fset function is executed here.

Any guidance is greatly appreciated.



source https://stackoverflow.com/questions/75271492/python-property-class-namespace-confusion

Comments

Popular posts from this blog

ValueError: X has 10 features, but LinearRegression is expecting 1 features as input

So, I am trying to predict the model but its throwing error like it has 10 features but it expacts only 1. So I am confused can anyone help me with it? more importantly its not working for me when my friend runs it. It works perfectly fine dose anyone know the reason about it? cv = KFold(n_splits = 10) all_loss = [] for i in range(9): # 1st for loop over polynomial orders poly_order = i X_train = make_polynomial(x, poly_order) loss_at_order = [] # initiate a set to collect loss for CV for train_index, test_index in cv.split(X_train): print('TRAIN:', train_index, 'TEST:', test_index) X_train_cv, X_test_cv = X_train[train_index], X_test[test_index] t_train_cv, t_test_cv = t[train_index], t[test_index] reg.fit(X_train_cv, t_train_cv) loss_at_order.append(np.mean((t_test_cv - reg.predict(X_test_cv))**2)) # collect loss at fold all_loss.append(np.mean(loss_at_order)) # collect loss at order plt.plot(np.log(al...

Sorting large arrays of big numeric stings

I was solving bigSorting() problem from hackerrank: Consider an array of numeric strings where each string is a positive number with anywhere from to digits. Sort the array's elements in non-decreasing, or ascending order of their integer values and return the sorted array. I know it works as follows: def bigSorting(unsorted): return sorted(unsorted, key=int) But I didnt guess this approach earlier. Initially I tried below: def bigSorting(unsorted): int_unsorted = [int(i) for i in unsorted] int_sorted = sorted(int_unsorted) return [str(i) for i in int_sorted] However, for some of the test cases, it was showing time limit exceeded. Why is it so? PS: I dont know exactly what those test cases were as hacker rank does not reveal all test cases. source https://stackoverflow.com/questions/73007397/sorting-large-arrays-of-big-numeric-stings

How to load Javascript with imported modules?

I am trying to import modules from tensorflowjs, and below is my code. test.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title </head> <body> <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@2.0.0/dist/tf.min.js"></script> <script type="module" src="./test.js"></script> </body> </html> test.js import * as tf from "./node_modules/@tensorflow/tfjs"; import {loadGraphModel} from "./node_modules/@tensorflow/tfjs-converter"; const MODEL_URL = './model.json'; const model = await loadGraphModel(MODEL_URL); const cat = document.getElementById('cat'); model.execute(tf.browser.fromPixels(cat)); Besides, I run the server using python -m http.server in my command prompt(Windows 10), and this is the error prompt in the console log of my browser: Failed to loa...