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]
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)
- [Django]-Python – Check if user is in team or not
- [Django]-AttributeError: 'CharField' object has no attribute 'model'
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:
-
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.) -
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.
- [Django]-How to properly show image stored from a remote file server to a django HTML template?
- [Django]-How can this be written on a single line?
- [Django]-Django-summernote image upload
- [Django]-Django replaces non-ascii characters with \ufffd
- [Django]-Can Django REST Swagger be used to generate static HTML documentation?
- [Django]-Django Generated polish plurals form in .po file not working
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.
- [Django]-Why Django translation does not use the base language in javascript?
- [Django]-Django deep serialization – follow reverse foreign key constraints
- [Django]-Urls.py redirect with URL reversal and parameters — is there any easier way?
- [Django]-Sphinx search in django admin
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.)
- [Django]-How to Show and hide form fields based on a selection from a dropdown menu in Django
- [Django]-Changing django-storages backend from from s3 to cloudfiles and dealing with old files
- [Django]-How do you access/configure summaries/snippets in Django Haystack
- [Django]-Passing a Django database pk id to Dash app
- [Django]-How do I successfully pass variables to my python social auth pipeline?