2

I have multiple variables with values that I like to access with the output from a string. I can get the string value but don't know how to convert the string "P2", so I can print or access the content of variable P2.

been searching for different ways to print lists and been using for loops, but I am lost, and can not find a solution.

P1 = [1.123, 10.34, 48.61]
P2 = [2.22, 11.34, 49.61]
P3 = [3.32, 12.34, 50.61]

g_line = ["N30","G54.1","P2",";\n"] 

def work_zero_p_num(): 
    for k, line in enumerate(g_line):
        if "P" in line:
            get_cur_work = line
    print(get_cur_work) # This line prints value "P2", 

work_zero_p_num()

the output i like to have is;

print(P2)
[2.22, 11.34, 49.61]

what i get from my code is

print(get_cur_work)
P2
BlueSheepToken
  • 5,751
  • 3
  • 17
  • 42
mollar
  • 21
  • 1

2 Answers2

0

You can use globals or locals to retrieve your variables as a dict.

P1 = [1.123, 10.34, 48.61]
P2 = [2.22, 11.34, 49.61]
P3 = [3.32, 12.34, 50.61]

g_line = ["N30","G54.1","P2",";\n"] 

def work_zero_p_num(): 
    for k, line in enumerate(g_line):
        if "P" in line:
            get_cur_work = line
    print(globals()[get_cur_work]) # This line prints the value of P2, 

work_zero_p_num()

A more detailed answer can be found here

BlueSheepToken
  • 5,751
  • 3
  • 17
  • 42
0

Have a look at globals() and id() from built-in functions: https://docs.python.org/3/library/functions.html#built-in-functions

Example:

def objname(obj):
    return [name for name, object_id in globals().items()
        if id(object_id) == id(obj)][0]

P2 = [2.22, 11.34, 49.61]


>>> print(P2)
[2.22, 11.34, 49.61]
>>> objname(P2)
'P2'
>>> print(objname(P2))
P2

You might be also interested in other functions such as: locals(), type(), dir(), getattr(), hasattr(), callable()

gbajson
  • 1,531
  • 13
  • 32
  • Thank you, I found a solution in getattr() by setting all of my P1, P2 .... in a separate file. – mollar Apr 19 '19 at 20:44