class first:
class second:
class third:
class forth:
val = "test"
I wanted to safely retrieve the variable 'val' and if 'val' doesn't exist i wanted to return False (instead of showing error)
I know i can use logical operator like this :
print first.second and first.second.third and first.second.third.forth and first.second.third.forth.val or False
or put it in a 'try ... except' block like this :
try :
print first.second.third.forth.val
except AttributeError:
pass
but both example above is just too long to read especially when they are too many nested classes
My question is, is there any other simpler way to do this? I wish for something like the ?. operator in C# or atleast function that can evaluate it safely and easy to read.
My question is similar to this question : How to know if an object has an attribute in Python
But the difference is that mine is in nested class, if i use hasattr() or getattr() I'll still have error when one the the class is missing like this :
>>> class first:
... class second:
... class third:
... class forth:
... val = "test"
...
>>> hasattr(first.second.third.forth.fifth,'val')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: class forth has no attribute 'fifth'
But it does give me an idea to create a function like this :
>>> def eval(cls, args, default=False):
... for arg in args.split('.') :
... if not hasattr(cls,arg) : return default
... cls = getattr(cls,arg)
... return cls
...
>>> eval(first,'second.third.forth.val','Default Value')
'test'
>>> eval(first,'second.third.forth.fifth','Default Value')
'Default Value'