Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python dynamically set non-instance class attributes

I am trying to add class attributes dynamically, but not at the instance level. E.g. what I can do manually as:

class Foo(object):
    a = 1
    b = 2
    c = 3

I'd like to be able to do with:

class Foo(object):
    dct = {'a' : 1, 'b' : 2, 'c' : 3}
    for key, val in dct.items():
        <update the Foo namespace here>

I'd like to be able to do this without a call to the class from outside the class (so it's portable), or without additional classes/decorators. Is this possible?

like image 737
gnr Avatar asked Aug 16 '26 00:08

gnr


1 Answers

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
like image 136
kindall Avatar answered Aug 18 '26 16:08

kindall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!