[Tutor] best way to dynamically set class variables?

Albert-Jan Roskam sjeik_appie at hotmail.com
Wed Nov 7 09:48:40 EST 2018


Hi,

Background: In my code I use sqlalchemy to read SQL server data. I want to write that data to HDF5 using pytables (see 'declaring a column descriptor': https://www.pytables.org/usersguide/tutorials.html). My question is not about pytables or sqlalchemy per se, but I thought it would be informative to mention this. 

What is the best way to dynamically set class variables? I am looking for a generalization of something like this:

class Parent: pass
class Child(Parent):
    col1 = 'str'
    col2 = 'int'

Several (im)possible solutions:

# -------
class Parent: pass
class_vars = dict(col1='str', col2='int')

# approach 1
Child = type('Child', (Parent,), class_vars)

# approach 2
class Child(Parent): pass
Child.__dict__.update( class_vars )  # AttributeError: 'mappingproxy' object has no attribute 'update'

# approach 3
class Child(Parent): pass
for k, v in class_vars.items():
    setattr(Child, k, v)

I initially chose approach #1, but I find this way of defining a class quite cryptic (but then, it's part of the language definition!). What's the best way to do this? I am using Python 3.5 (Windows). Thanks in advance!

Best wishes,
Albert-Jan


More information about the Tutor mailing list