0

In unix shell script: if I call function_name "${!variable}" -> variable will replaced during the execution/runtime

is there something alternative exists in python? there are some other logic involved prior creating the variable. But I'm interested in {!variable} alternative.

change198
  • 1,183
  • 1
  • 11
  • 38
  • You have an XY problem, in that you are trying to store variable names as data in the first place. You probably want to use a `dict`, not a loose assortment of individual variables, to hold your data. – chepner May 05 '20 at 13:40

2 Answers2

2

You are looking for the eval function:

a = "there"
b = "a"
eval(b)

Yielding the output:

'there'

Of course, the eval function, while being a bit more verbose than the bash indirect variable reference, is also much more versatile, as you can have the indirectly referenced variable (b in this case), contain any python expression.

Amitai Irron
  • 1,812
  • 1
  • 10
  • 11
0

In python functions are 1st class objects. Which means you can pass them around just like any variable.

def print_this():
    print('this')

def print_that():
    print('that')

p1 = print_this
p2 = print_that

p1()
p2()

So you don't need to use eval.

sureshvv
  • 3,929
  • 1
  • 23
  • 31
  • You are making some assumption on why th OP needs to access a variable by name. You may be right, but the strict answer to his question is using `eval`. I also do not think that OP is trying to place the name of a function in a variable, but simply pass the content of name of a variable to a function (I'm no **bash** expert). – Amitai Irron May 05 '20 at 11:53
  • 1
    eval can be dangerous and should be used only as a last resort. I would not suggest that as a first step. – sureshvv May 05 '20 at 12:05
  • I checked the **bash** syntax for functions, and I think you misinterpreted the OP's question. What OP wanted was not to called a function named in a variable, but call a known function, and pass to it the content of a variable who's name was in another variable. The answer you provided is a good answer to a different question. – Amitai Irron May 06 '20 at 07:18
  • If that is the case, then @chepner answer to use a `dict` is the correct one. Cannot recommend `eval`. – sureshvv May 07 '20 at 06:17