Class factory to produce simple struct-like classes?
If you're running python <2.6 or would like to extend your class to do more stuff, I would suggest using the type()
builtin. This has the advantage over your solution in that the setting up of __dict__
happens at class creation rather than instantiation. It also doesn't define an __init__
method and thus doesn't lead to strange behavior if the class calls __init__
again for some reason. For example:
def Struct(*args, **kwargs):
name = kwargs.pop("name", "MyStruct")
kwargs.update(dict((k, None) for k in args))
return type(name, (object,), kwargs)
Used like so:
>>> MyStruct = Struct("forename", "lastname")
Equivalent to:
class MyStruct(object):
forename = None
lastname = None
While this:
>>> TestStruct = Struct("forename", age=18, name="TestStruct")
Is equivalent to:
class TestStruct(object):
forename = None
age = 18
Update
Additionally, you can edit this code to very easily prevent assignment of other variables than the ones specificed. Just change the Struct() factory to assign __slots__
.
def Struct(*args, **kwargs):
name = kwargs.pop("name", "MyStruct")
kwargs.update(dict((k, None) for k in args))
kwargs['__slots__'] = kwargs.keys()
return type(name, (object,), kwargs)
As others have said, named tuples in Python 2.6/3.x. With older versions, I usually use the Stuff class:
class Stuff(object):
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
john = Stuff(forename='John', surname='Doe')
This doesn't protect you from mispellings though. There's also a recipe for named tuples on ActiveState:
http://code.activestate.com/recipes/500261/
If you're using Python 2.6, try the standard library namedtuple class.
>>> from collections import namedtuple
>>> Person = namedtuple('Person', ('forename', 'surname'))
>>> person1 = Person('John', 'Doe')
>>> person2 = Person(forename='Adam', surname='Monroe')
>>> person1.forename
'John'
>>> person2.surname
'Monroe'
Edit: As per comments, there is a backport for earlier versions of Python