Correct type for a simple "bag of attributes" namespace object

Peter Otten __peter__ at web.de
Sun Aug 3 07:23:42 EDT 2014


Albert-Jan Roskam wrote:

> 
> 
> ----- Original Message -----
> 
>> From: Peter Otten <__peter__ at web.de>
>> To: python-list at python.org
>> Cc:
>> Sent: Sunday, August 3, 2014 11:37 AM
>> Subject: Re: Correct type for a simple "bag of attributes" namespace
>> object
>> 
>> 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:
> 
> Yes, I know that it is equivalent, but I have always found it kind of ugly
> to use class() just to bundle a number of items. 

But that's what you are doing, you just spell it differently.

> Like you are 'announcing
> OOP' (not sure how to put this into words), and then it's merely a simple
> bundle. Or maybe it's just me being silly, because it's even in the Python
> tutorial: https://docs.python.org/2/tutorial/classes.html#odds-and-ends
> 
>>>>>  import sys
>>>>>  sys.getsizeof(employee)
>> 976
>>>>>  class Employee: pass
>> ...
>>>>>  employee = Employee()
>>>>>  employee.name = "John Doe"
>>>>>  employee.position = "Python programmer"
>>>>>  sys.getsizeof(employee)
>> 64
> Wow, I was not aware of that at all. So they are not equivalent after all.

I think you are misunderstanding what I was trying to say; so to be 
explicit:

>>> class Employee: pass
... 
>>> sys.getsizeof(Employee)
976

i. e. you have a per-class and per-instance memory consumption. The latter 
is smaller, so with regards to memory consumption instantiating only pays 
off when there is more than one employee.




More information about the Python-list mailing list