For debugging purposes I need to know the values of some variables in Python. But, I don't want create a dictionary with all variables and don’t want to add every new variable that I want to test at some point to a dictionary, especially when it comes to lists and their content, which is often procedurally generated.
So is there an alternative to just taking input as a string and then executing it by exec() or using print() and hardcoded variables?
Yes, there is a way. You can use the locals() function to get a dictionary of all variables. For example:
a=5
b=locals()["a"]
Now b will get the value of a, i.e. 5.
However, while you can do this doesn't mean you should do this. There may be something wrong in the structure of your program if you want to access variables by using their name stored in a string.
Related
I didn't try anything because I don't even know where to start...
the program would associate every item of the list to the variables like (name)1, (name)2, (name)3, and so on to the number of items the list has.
prdt = ["WD40", "001", "oleo de carro, 1L", "liquidos", "seccao 1", 5, 30]
prdt1 ="WD40"
prdt2 ="001"
prdt3 ="oleo de carro, 1L"
prdt4 ="liquidos"
a program that creates a variable incremented by 1 in a for a loop.
Basically with python version above 3.8 you can use eval and walrus operator in order to achieve this behaviour. You will get variables with names corresponding to your list items
for idx, item in enumerate(prdt):
eval(f"({item}{idx}:={item})")
If you look at this weird syntax in eval it's walrus operator := combined with a parenthesis and all that in a f-string. Very unreadable and ugly solution imho, but eval only allows for expressions, NOT compound statements (so you cannot use the regular assignment with = ).
And you have int values in your list, which will cause the above code to fail, since var name in python cannot be an int... 5=5 is not a legal code, neither are values with spaces...Overall sorry to say, but this question does not make too much sense to be honest.
But in general it sounds like a terrible idea to be honest (whatever is your usecase). If you need to associate specific names with values you should use dict probably.
I have the following parameters in a Python file that is used to send commands pertaining to boundary conditions to Abaqus:
u1=0.0,
u2=0.0,
u3=0.0,
ur1=UNSET,
ur2=0.0,
ur3=UNSET
I would like to place these values inside a list and print that list to a .txt file. I figured I should convert all contents to strings:
List = [str(u1), str(u2), str(u3), str(ur1), str(ur2), str(ur3)]
This works only as long as the list does not contain "UNSET", which is a command used by Abaqus and is neither an int or str. Any ideas how to deal with that? Many thanks!
UNSET is an Abaqus/cae defined symbolic constant. It has a member name that returns the string representation, so you might do something like this:
def tostring(v):
try:
return(v.name)
except:
return(str(v))
then do for example
bc= [0.,1,UNSET]
print "u1=%s u2=%s u3=%s\n"%tuple([tostring(b) for b in bc])
u1=0. u2=1 u3=UNSET
EDIT simpler than that. After doing things the hard way I realize the symbolic constant is handled properly by the string conversion so you can just do this:
print "u1=%s u2=%s u3=%s\n"%tuple(['%s'%b for b in bc])
I have some code that generates two strings - digit_ and 'x', where x is an integer. My gut feeling is that this is a stupid question, but I can't find an answer online. I have variables called digit_1, digit_2 ... etc up to digit_9. How can I call the correct one of these without using a really long if/elif function? Is there a way of calling a variable from a concatenation of it's name?
Sam
The cleanest way is to put the variables into a list or a dictionary, and then access them by index or by name.
No, there isn't a good way to "create" variable names and access them.
However, you can just use a list, and index into it instead.
I have a bunch of lists in a module (say student_data) which I import in my file. All the list are of type student[1-100]. Now depending on user input I wish to iterate through the corresponding list. Lets say the user inputs 10 then I want to print the contents of list student10. How do I go about doing this?
Input in variable i
for x in student_data.student+i:
print x
You should put all of the lists into a big list of lists.
Then you use can the standard student_data.student_lists[index] to get an individual list.
Winston Ewert is definitely correct in what the right way to do this would be.
However, if you're locked into your existing data structure, what you want is to use the getattr function... this allows programmatic access to a specified attribute. In your case, getattr(student_data, "student%d" % (i,))
I have a Dictionary of Classes where the classes hold attributes that are lists of strings.
I made this function to find out the max number of items are in one of those lists for a particular person.
def find_max_var_amt(some_person) #pass in a patient id number, get back their max number of variables for a type of variable
max_vars=0
for key, value in patients[some_person].__dict__.items():
challenger=len(value)
if max_vars < challenger:
max_vars= challenger
return max_vars
What I want to do is rewrite it so that I do not have to use the .iteritems() function. This find_max_var_amt function works fine as is, but I am converting my code from using a dictionary to be a database using the dbm module, so typical dictionary functions will no longer work for me even though the syntax for assigning and accessing the key:value pairs will be the same. Thanks for your help!
Since dbm doesn't let you iterate over the values directly, you can iterate over the keys. To do so, you could modify your for loop to look like
for key in patients[some_person].__dict__:
value = patients[some_person].__dict__[key]
# then continue as before
I think a bigger issue, though, will be the fact that dbm only stores strings. So you won't be able to store the list directly in the database; you'll have to store a string representation of it. And that means that when you try to compute the length of the list, it won't be as simple as len(value); you'll have to develop some code to figure out the length of the list based on whatever string representation you use. It could just be as simple as len(the_string.split(',')), just be aware that you have to do it.
By the way, your existing function could be rewritten using a generator, like so:
def find_max_var_amt(some_person):
return max(len(value) for value in patients[some_person].__dict__.itervalues())
and if you did it that way, the change to iterating over keys would look like
def find_max_var_amt(some_person):
dct = patients[some_person].__dict__
return max(len(dct[key]) for key in dct)