This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 5 years ago.
I have a list of commands that I want to iterate over so I've put those commands into a list. However, I want to also use that list as strings to name some files. How do I convert variable names to strings?
itemIDScore = """SELECT * from anytime;"""
queryList = [itemIDScore, accountScore, itemWithIssue, itemsPerService]
for x in queryList:
fileName = x+".txt"
cur.execute(x) #This should execute the SQL command
print fileName #This should return "itemIDScore.txt"
I want fileName to be "itemIDScore.txt" but itemIDScore in queryList is a SQL query that I'll use elsewhere. I need to name files after the name of the query.
Thanks!
I don't think you may get name of the variable as string from the variable object. But instead, you may create the list of string of your variables as:
queryList = ['itemIDScore', 'accountScore', 'itemWithIssue', 'itemsPerService']
Then you may access the value of variable from the variable name string using the globals() function as:
for x in queryList:
fileName = "{}.txt".format(x)
data = globals()[x]
cur.execute(data)
As the globals() document say:
Return a dictionary representing the current global symbol table. This is always the dictionary of the current module (inside a function or method, this is the module where it is defined, not the module from which it is called).
As far as I know, there is no easy way to do that, but you could simply use a dict with what currently are variable names as keys, e.g.:
queries = {
'itemIDScore': 'sql 1',
'accountScore': 'sql 2',
...
}
for x in queries:
fileName = x + ".txt"
cur.execute(queries[x])
print fileName
This would also preserve your desired semantics without making the code less readable.
I think you would have an easier time storing the names explicitly, then evaluating them to get their values. For example, consider something like:
itemIDScore = "some-long-query-here"
# etc.
queryDict = dict( (name,eval(name)) for name in ['itemIDScore', 'accountScore', 'itemWithIssue', 'itemsPerService'] )
for k in queryDict:
fileName = k+".txt"
cur.execute(queryDict[k])
You can use the in-built str() function.
for x in queryList:
fileName = str(x) + ".txt"
cur.execute(x)
Related
I wonder if there is a way to create variables automatically using strings, e.g. I have the following code (which does not work properly in Python):
def function(lst1, string1):
lst2 = 'processed_' + string1
lst2 = [] #here I created a string called lst2, but I want to use the string as the variable name.
for i in range(len(lst1)):
if abs(lst1[i]) >= 0.0001 :
lst2.append(i)
return lst2
function(list1, 'price') # list1 is a list which contains the index for column numbers, e.g., [1,2,3]
function(list1, 'promotion')
function(list1, 'calendar')
I would expect that with the function I would be able to create lists such as processed_price, processed_promotion, and processed_calendar, and the function will return these lists.
However the code above would not work as in Python. I wonder how should I write the code properly to achieve the same goal?
getattr(object, name, [default])
setattr(object, name, value)
To get or set values for a variable named via a string, use one of the above as appropriate. However, any time you use user input, it can be a source of injection attacks — the user could use a name that you did not expect them to use but the name is valid so the user gets access to data they should not have access to.
So it is usually advisable to use the user input as a key into a dictionary you define.
dictionary = {
'apple': 'my_value'
}
dictionary[user_input] = 'their_value'
This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 1 year ago.
I have two lists in python
targetvariables = ['a','b','c']
featurevariables = ['d','e','f']
I would like to create three lists such as the following:
a_model = ['a','d','e','f']
b_model = ['b','d','e','f']
c_model = ['c','d','e','f']
I have about 15 target variables and 100+ feature variables so is there a way to do this in a loop of some kind? I tried but I couldnt work out how to assign a list name from a changing variable:
for idx,target in enumerate(targetvariables):
target +'_model' = targetvariables[idx] + featurevariables
SyntaxError: can't assign to operator
The end goal is to test machine learning models and to make things easier I would like to simply call:
df[[a_model]]
to then use in the ML process.
Short answer: DO NOT DO THIS!
By doing this you're corrupting the global namespace and that's not recommended. If you really need to do this, this is how:
for target_var in targetvariables:
# access the global namespace and modify it
globals()[f'{target_var}_model'] = [target_var] + featurevariables
Alternative #1
Instead of storing the lists in variables, store them in a container, for example, a dict:
models = {} # create an empty dict
for target_var in targetvariables:
# the same as the last example but with 'models' instead of 'globals()'
models[f'{target_var}_model'] = [target_var] + featurevariables
Then access the lists like so:
>>> models['a_model']
['a','d','e','f']
You can also easly change the code so that the keys of the dict would be the variable name itself, without "_model".
Alternative #2
Instead of storing the lists, create them on the fly with a function:
def get_model(target_var):
return [target_var] + featurevariables
Then access the lists like so:
>>> get_model('a')
['a','d','e','f']
I have dumped a couple of variables I need to store in a json object as shown here-
def write_json():
variable = {}
variable['p_id'] = p_id
variable['s_id'] = s_id
variable['t_id'] = t_id
variable['b_start'] = b_start
variable['b_end'] = b_end
variable['wsp_after'] = wsp_after
variable['h_id'] = h_id
variable['word'] = word
variable['norm_word'] = norm_word
variable['lemma'] = lemma
variable['pos'] = pos
variable['ner'] = ner
variable['dep'] = dep
variable['quote'] = quote
variable['ch_id'] = ch_id
with open('variable.json', 'w') as fp:
json.dump(variable,fp, sort_keys = True)
I want to write a piece of code that would automatically get these variables assigned appropriately as would happen if you wrote from 'X.py' import *
This is what I tried-
def get_variables():
with open('variable.json', 'r') as fp:
variable = json.load(fp)
for key in variable:
global key
key = variable[key]
However, when I tried to print the original value-
print t_id
NameError: name 't_id' is not defined
What do I need to do to achieve what I want rather than cumbersomely typing
t_id = variable['t_id']
.
.
.
For every variable I have dumped?
Your current code doesn't work because the following lines just bind (and rebind, for the later values in the loop) a global variable named 'key':
global key
key = variable[key]
While I'm not sure your design is really a good one, if you're sure you want all the values from your json file as global variables, I'd replace the loop with:
globals().update(variable)
The globals() function returns a dictionary that contains all the current module's global variables. Unlike the dictionary you get from locals() (which may be a copy of the local namespace, not the actual implementation of it), you can modify the globals() dictionary and use the variables like normal afterwards.
Here's the solution -
with open('variable.json', 'r') as fp:
variable = json.load(fp)
for key in variable.keys():
exec(key + " = variable['" + key + "']")
The problem before was that each 'key' was a string, not an object.
Using the exec function successfully parses each string into an object and using it as given above gets the results as was asked in the question.
This may be a very simple question, but how can I use a string for the name of a class/object declaration? I'm working with PySide, and I have code that will make a text input for every entry in an array.
i=0
d = {}
for name in mtlName:
i = i+1
curOldLabel = d["self.oldLabel" + str(i)]
So now I have to just decalre QtGui.QLineEdit() as what curOldLabel equals (self.oldLabel1 = QtGui.QLineEdit(), self.oldLabel2 = QtGui.QLineEdit(), etc). How do I tell it not to overwrite curOldLabel, but instead use the string as the name for this object?
Your best bet is to use another dictionary to store those objects. It's safe, it's easy to use and it has fast lookup. You don't want to be creating normal variables with dynamic names in most scenarios.
This question already has answers here:
Calling a function of a module by using its name (a string)
(18 answers)
Closed 9 years ago.
Some days ago I was searching on the net and I found an interesting article about python dictionaries. It was about using the keys in the dictionary to call a function. In that article the author has defined some functions, and then a dictionary with key exactly same as the function name. Then he could get an input parameter from user and call the same method (something like implementing case break)
After that I realised about the same thing but somehow different. I want to know how I can implement this.
If I have a function:
def fullName( name = "noName", family = "noFamily" ):
return name += family
And now if I have a string like this:
myString = "fullName( name = 'Joe', family = 'Brand' )"
Is there a way to execute this query and get a result: JoeBrand
For example something I remember is that we might give a string to exec() statement and it does it for us. But I’m not sure about this special case, and also I do not know the efficient way in Python. And also I will be so grateful to help me how to handle that functions return value, for example in my case how can I print the full name returned by that function?
This does not exactly answer your question, but maybe it helps nevertheless:
As mentioned, eval should be avoided if possible. A better way imo is to use dictionary unpacking. This is also very dynamic and less error prone.
Example:
def fullName(name = "noName", family = "noFamily"):
return name + family
functionList = {'fullName': fullName}
function = 'fullName'
parameters = {'name': 'Foo', 'family': 'Bar'}
print functionList[function](**parameters)
# prints FooBar
parameters = {'name': 'Foo'}
print functionList[function](**parameters)
# prints FoonoFamily
You could use eval():
myString = "fullName( name = 'Joe', family = 'Brand' )"
result = eval(myString)
Beware though, eval() is considered evil by many people.
I know this question is rather old, but you could do something like this:
argsdict = {'name': 'Joe', 'family': 'Brand'}
globals()['fullName'](**argsdict)
argsdict is a dictionary of argument, globals calls the function using a string, and ** expands the dictionary to a parameter list. Much cleaner than eval. The only trouble lies in splitting up the string. A (very messy) solution:
example = 'fullName(name=\'Joe\',family=\'Brand\')'
# Split at left parenthesis
funcname, argsstr = example.split('(')
# Split the parameters
argsindex = argsstr.split(',')
# Create an empty dictionary
argsdict = dict()
# Remove the closing parenthesis
# Could probably be done better with re...
argsindex[-1] = argsindex[-1].replace(')', '')
for item in argsindex:
# Separate the parameter name and value
argname, argvalue = item.split('=')
# Add it to the dictionary
argsdict.update({argname: argvalue})
# Call our function
globals()[funcname](**argsdict)