Warm tip: This article is reproduced from stackoverflow.com, please click
pandas python

Dynamically generated class and variable name

发布于 2020-03-28 23:17:18

I have csv like this,

name,job
Jay,engineer
Kay,layer
hop,warrior

then I load this in pandas datafrme and put in DB

df = pd.read_csv('job.csv')

for index,row in df.iterrows():
   q = Issue(name = row[0],job = row[1])
   q.save()
   print ("Register : ",row[0] , " / ",row[1])
exit()

It works well but now, I want to generalize this code as function like this below.

def stor_db(classname):
    df = pd.read_csv(classname + '.csv')

    for index,row in df.iterrows():
       q = `classname`(
           `title[0]ofdf` = row[0],
           `title[1]ofdf` = row[1])
       q.save()
       print ("Register : ",row[0] , " / ",row[1])
    exit()

I need to dynamically make variable/class name.

It possible for python and pandas??

Questioner
whitebear
Viewed
33
polku 2020-01-31 19:11

Everything in Python is an object, including classes.

The builtin type() is mostly used to check a variable type but there is a least known usage. If type() is used with 3 parameters, it creates a new type Object.

The first parameter is the name of your class, the second is the tuple of bases classes for inheritance, the third is a dict that will becomes the __dict__ attribute.

Example = type("Example", (object,), {"a" : 0})

# equivalent to

class Example(object):
    def __init__(self):
        self.a = 0

So you can do something like that

   Example = type(classname, (object,), {title[0]ofdf = row[0], title[1]ofdf = row[1]})

Inherit a base class with the needed methods instead of object and you'll have the common methods you need.

EDIT:

If your classes are Django models it completely changes the nature of the problem and this solution is not pertinent. Your models already exists so you don't really want to create classes dynamically, but pick the model dynamically.

I think I'll go with a load_from_csv method using __class__.__name_, shared via inheritance and use kwargs as parameters to the constructors (assuming the models attributes exactly match the csv columns).