I have two numpyarrays named dec_pair and dec_community in a module named config.py, initialized to zero:
dec_pair = numpy.zeros(200)
dec_community = numpy.zeros(200)
Now, I am trying to access them from some other module, say roc.py, where their names are being formed based on a input variable, i.e.
import config
def dosomething(name):
local_name = 'config.py'+name
eval(local_name)[i:] += 1
where name can be pair or community. The issue is, eval(local_name) is returning the length of the numpy array i.e. 200 here and not the array itself, which gives me this error:
ValueError: cannot slice a 0-d array
However, when I do the same thing on the python interpreter, it runs smoothly :
>>> dec_pair = numpy.zeros(5)
>>> name = 'pair'
>>> local_name = 'dec_'+name
>>> eval(local_name)
array([ 0., 0., 0., 0., 0.])
Any idea as to what I am doing wrong and what would be the correct way to do it ?
What you’re trying to do looks like a bad idea (although I’m having a hard time figuring out what you’re trying to do).
My first instinct is to say that you probably want
numpy.zeros(200)instead ofnumpy.array(200)in your config file.Second, if this stuff is imported, you could probably use
globals()[local_name]orvars(config)[local_name]to get your data rather thaneval, although that is still definitely bad practice (in other words, Please don’t do this — see point 3).Third, when you don’t know the name of the variable ahead of time, you should be using a dictionary to begin with e.g.
Now you just access them in your function as:
If you wanted an easier handle on
dec_pairanddec_community, you could doconfig.pylike this:Although I would probably say that it’s best to keep the data referenced in only 1 place so I would caution against doing this unless you really need to keep an API consistent or something.
Finally, you haven’t mentioned what the value of the variable
iis — accessing variables outside of the current namespace is often risky, and variables namediare probably even more risky.