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

How to show number of registered users in Laravel based on usertype?

i'm trying to display data from the database in the admin dashboard i used this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count(); echo $users; ?> and i have successfully get the correct data from the database but what if i want to display a specific data for example in this user table there is "usertype" that specify if the user is normal user or admin i want to user the same code above but to display a specific usertype i tried this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count()->WHERE usertype =admin; echo $users; ?> but it didn't work, what am i doing wrong? source https://stackoverflow.com/questions/68199726/how-to-show-number-of-registered-users-in-laravel-based-on-usertype

Why is my reports service not connecting?

I am trying to pull some data from a Postgres database using Node.js and node-postures but I can't figure out why my service isn't connecting. my routes/index.js file: const express = require('express'); const router = express.Router(); const ordersCountController = require('../controllers/ordersCountController'); const ordersController = require('../controllers/ordersController'); const weeklyReportsController = require('../controllers/weeklyReportsController'); router.get('/orders_count', ordersCountController); router.get('/orders', ordersController); router.get('/weekly_reports', weeklyReportsController); module.exports = router; My controllers/weeklyReportsController.js file: const weeklyReportsService = require('../services/weeklyReportsService'); const weeklyReportsController = async (req, res) => { try { const data = await weeklyReportsService; res.json({data}) console

How to split a rinex file if I need 24 hours data

Trying to divide rinex file using the command gfzrnx but getting this error. While doing that getting this error msg 'gfzrnx' is not recognized as an internal or external command Trying to split rinex file using the command gfzrnx. also install'gfzrnx'. my doubt is I need to run this program in 'gfzrnx' or in 'cmdprompt'. I am expecting a rinex file with 24 hrs or 1 day data.I Have 48 hrs data in RINEX format. Please help me to solve this issue. source https://stackoverflow.com/questions/75385367/how-to-split-a-rinex-file-if-i-need-24-hours-data