Correct type for a simple "bag of attributes" namespace object
Peter Otten
__peter__ at web.de
Sun Aug 3 05:37:04 EDT 2014
Albert-Jan Roskam wrote:
> I find the following obscure (to me at least) use of type() useful exactly
> for this "bag of attributes" use case:
>>>> employee = type("Employee", (object,), {})
>>>> employee.name = "John Doe"
>>>> employee.position = "Python programmer"
>>>> employee.name, employee.position, employee
> ('John Doe', 'Python programmer', <class '__main__.Employee'>)
Are you sure you know what you are doing? The above is equivalent to
>>> class employee:
... name = "John Doe"
... position = "Python programmer"
...
>>> employee.name, employee.position, employee
('John Doe', 'Python programmer', <class '__main__.employee'>)
>>> type(employee)
<class 'type'>
Basically you are using classes as instances. While there is no fundamental
difference between classes and instances in Python you'll surprise readers
of your code and waste some space:
>>> import sys
>>> sys.getsizeof(employee)
976
>>> class Employee: pass
...
>>> employee = Employee()
>>> employee.name = "John Doe"
>>> employee.position = "Python programmer"
>>> sys.getsizeof(employee)
64
More information about the Python-list
mailing list