Python lazy hasattr()
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.
Python lazy hasattr()
Thu 30 September 2010Python 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.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK