[Django]-Python: how to use variables as a string?

8👍

locals() returns a dictionary of local variables. Similarly, globals() returns a dictionary of global variables. You can find the variable and its value in one of those, depending on where it was defined.

for i in range(1,101):
    if ('var%s' % i) in locals():
        print 'var%s is not None' % i
        print locals()['var%s' % i]
👤kichik

5👍

I wish you hadn’t buried your actual requirement in the tenth comment underneath the main question. Actually, it appears that what you want is to dynamically get a property of a class – in this instance, a field in a Django model. That’s simple: you just do:

getattr(instance, varname)

2👍

You can modify class attributes dynamically:

class A(object):
    pass
for i in range(100):
    setattr(A, "var%i" % i, i)

creates a class with 100 attributes called A.var0 to A.var99. There are two problems with this approach:

  1. The attributes are quite inconvenient to access. (This is possible with getattr(), but having them in a list would make iterating over them so much easier.)

  2. If class A has a custom metaclass, it is unclear how that metaclass deals with the dynamically created attributes.

From a quick glance at the Django source code, I can see that django.db.models.Model indeed has a custom metaclass, and indeed all attributes must already be defined at class creation time, so the above approach won’t work. You’ll have to create the complete class dictionary before actually creating the class. Here is one approach to do so:

model_dict = {}
for i in range(100):
    model_dict["var%i" % i] = models.CharField(max_length=10)
model_dict["var_list"] = model_dict.values()
MyModel = type("MyModel", (models.Model,), model_dict)

This uses the three-parameter form of type() to dynamically create a type. This part addresses problem 2.

To address problem 1, the above code exposes also adds an attribute to the class that allows to acces all the models.CharField instances as a list rather than by name.

2👍

I think you are looking for the eval command.

Hope this helps,

Regards, Maecky

👤Maecky

1👍

Couple different ways to do it, either get the variable from the globals or locals dictionary like so:
globals()['var1']

or import __main__ and use getattr(__main__,'var1')

throw those into a for loop, assigning the variable name to a string andhave it returned eg

if your testing that the class exists, use a try except

import __main__

for i in range(1,101):
  try:
    func = getattr(__main__,'var%s' % i)
    if func is not None:
      print 'var%s is not None' % i
  except:
    print 'var%s does not exist'

if it’s buried in a class use the class name rather than __main__. If the class name is var%s use getattr on func in the loop above to grab whatever it is you need out of each class.

👤Kyle G

1👍

I think that a list or dictionary actually would be the most appropriate way to solve your problem. In Python, data structures can hold others objects. This includes objects that you create yourself because there is no technical distinction from the programmer’s point of view between the types (classes) you define and the ones that are native to Python (string, int, etc.)

Leave a comment