Judging from your example code, you want to do this at the same time you create the class. In this case, assuming you're using CPython, you can use locals()
.
class Foo(object):
locals().update(a=1, b=2, c=3)
This works because while a class is being defined, locals()
refers to the class namespace. It's implementation-specific behavior and may not work in later versions of Python or alternative implementations.
A less dirty-hacky version that uses a class factory is shown below. The basic idea is that your dictionary is converted to a class by way of the type()
constructor, and this is then used as the base class for your new class. For convenience of defining attributes with a minimum of syntax, I have used the **
convention to accept the attributes.
def dicty(*bases, **attrs):
if not bases:
bases = (object,)
return type("<from dict>", bases, attrs)
class Foo(dicty(a=1, b=2, c=3)):
pass
# if you already have the dict, use unpacking
dct = dict(a=1, b=2, c=3)
class Foo(dicty(**dct)):
pass
This is really just syntactic sugar for calling type()
yourself. This works fine, for instance:
class Foo(type("<none>", (object,), dict(a=1, b=2, c=3))):
pass