8

Python lazy hasattr()

 3 years ago
source link: https://blog.mathieu-leplatre.info/python-lazy-hasattr.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
Python lazy hasattr()

Python lazy hasattr()

Thu 30 September 2010

Python hasattr() evaluates the specified attribute, which may not be desired !

class Attr(object):
    def __get__(self, obs, cls=None):
        print "evaluated"
        return 0

class ClassA(object):
    a = Attr()

    @property
    def b(self):
        print "evaluated"
        return 0

>>> c = ClassA()
>>> c.a
evaluated
0
>>> c.b
evaluated
0

Now note that hasattr() evaluates the lazy attribute !

>>> hasattr(c, 'a')
evaluated
True
>>> hasattr(c, 'b')
evaluated
True

Let us fix that !

def lazyhasattr(obj, name):
    return any(name in d for d in (obj.__dict__,
                                   obj.__class__.__dict__))

>>> c = ClassA()
>>> lazyhasattr(c, 'a')
True
>>> lazyhasattr(c, 'b')
True

#tips, #python - Posted in the Dev category


© Copyright 2020 by Mathieu Leplatre. mnmlist Theme

Content licensed under the Creative Commons attribution-noncommercial-sharealike License.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK