Question

NewType=type('nt',(object,),{'x':'hello'})
n=NewType()
n.x
'hello'

How do I obtain the dict {'x':'hello'} from n?

Failed attempts: n.__bases__, n.__dir__, n.__dict__

Was it helpful?

Solution

You have a class attribute, so NewType.__dict__ would work.

Alternative routes would be:

type(n).__dict__
vars(NewType)
vars(type(n))

Demo:

>>> NewType=type('nt',(object,),{'x':'hello'})
>>> n=NewType()
>>> n.x
'hello'
>>> NewType.__dict__
dict_proxy({'__dict__': <attribute '__dict__' of 'nt' objects>, 'x': 'hello', '__module__': '__main__', '__weakref__': <attribute '__weakref__' of 'nt' objects>, '__doc__': None})
>>> type(n).__dict__
dict_proxy({'__dict__': <attribute '__dict__' of 'nt' objects>, 'x': 'hello', '__module__': '__main__', '__weakref__': <attribute '__weakref__' of 'nt' objects>, '__doc__': None})
>>> vars(NewType)
dict_proxy({'__dict__': <attribute '__dict__' of 'nt' objects>, 'x': 'hello', '__module__': '__main__', '__weakref__': <attribute '__weakref__' of 'nt' objects>, '__doc__': None})
>>> vars(type(n))
dict_proxy({'__dict__': <attribute '__dict__' of 'nt' objects>, 'x': 'hello', '__module__': '__main__', '__weakref__': <attribute '__weakref__' of 'nt' objects>, '__doc__': None})

The class dictionary has a few more attributes in it (including __dict__ itself).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top