Does there exist special class in python to create empty objects? I tried object(), but it didn't allow me to add fields. I want to use it like this:
obj = EmptyObject()
obj.foo = 'far'
obj.bar = 'boo'
Should I each time(in several independent scripts) define new class like this?
class EmptyObject:
pass
I use python2.7
If you are looking for a place holder object to which you can add arbitrary static members, then the closest I got is an empty lambda function.
Remember:
obj
is not an object of a class, object doesn't mean class instance, because in Python classes and functions are objects at runtime just like class instancesThere is no
types.SimpleNamespace
in Python 2.7, you could usecollections.namedtuple()
for immutable objects instead:Or
argparse.Namespace
:You can create a new type dynamically with the fields you want it to have using the
type
function, like this:This is not entirely what you want though, since it will have a custom type, not an empty type.
types.SimpleNamespace
was introduced with Python 3.3 to serve this exact purpose. The documentation also shows a simple way to implement it yourself in Python, so you can add it to your pre-Python 3.3 setup and use it as if it was there (note that the actual implementation is done in C):But of course, if you don’t need its few features, a simple
class Empty: pass
does just the same.