How to add class attributes to a python class programmatically?

Most of the time we add variables to a python class via inheritance. However, sometimes inheritance is not the way to go, since between the classes there is no “is-a” relationship.


I have been using Django framework and I encountered a case where I had two models that stored very similar things but still were not a proper inheritance “is-a” relationship. I was doing a crowdsourced dictionary project where the users add their own words and the words get added to the public only after a reviewer accepted them. So I had two models, Word and UserWord and for some specifics of the project UserWord was not a Word, thus inheritance was out of question.

But copy-paste programming is just not right. There must be a better way! Right?

As it turns out, a class’s body is just a code block that is executed in a special context. So, adding to locals() really adds a variable to class properties. My first version of the code looked like this:

Now, we only need to retouch this a bit to make it clear that we are copying field properties.

That’s it. Neat, isn’t it?

How to reuse this concept?

With this method in mind you can copy from a different class anything you’d like.
For exaple, in the following snippet I copy all the class attributes but not the functions and subclasses.

I hope this gets your creative juices going. A python class’s body is really just a special local context where normal code gets executed.

Photo by Mitchell Griest on Unsplash



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Barnabas Szabolcs

Data scientist and enthusiastic programmer, specialized in full-stack development (python, django, vue, angular). Founder of