dictionary - Python: Making a read-only property accessible via **vars(some_class) -
i use idiom '{var_name}'.format(**vars(some_class))
.
however, when use property, cannot use properties value.
consider program:
#!/usr/bin/env python class foo(object): def __init__(self): self._bar = none self.baz = 'baz here' @property def bar(self): if not self._bar: # calculate value... self._bar = 'bar here' return self._bar if __name__ == '__main__': foo = foo() # works: print('{baz}'.format(**vars(foo))) # gives: keyerror: 'bar' print('{bar}'.format(**vars(foo)))
question:
is there way make properties value accessible via **vars(some_class)
?
short answer: no, it's not possible use .format(**vars(object))
want, since properties not use __dict__
, vars
documentation:
vars(...)
vars([object])
-> dictionary
- without arguments, equivalent
locals()
.- with argument, equivalent
object.__dict__
.
however can achieve want using different format specifiers, example attribute lookup:
in [2]: '{.bar}'.format(foo()) out[2]: 'bar here'
note have add leading .
(dot) names , want.
side note: instead of using .format(**vars(object))
should use format_map
method:
in [6]: '{baz}'.format_map(vars(foo())) out[6]: 'baz here'
calling format_map
dict
argument equivalent calling format
using **
notation, more efficient, since doesn't have kind of unpacking before calling function.
Comments
Post a Comment