Use string as function arguments

Question:

Hey I am trying to use a string in a function but when I put it in the ” stay.
The result I am trying to get is this.

foo(bar = 1)

But using a string like this.

string = 'bar = 1'

foo(string)

But it comes out like.

foo('bar = 1')

Thank you.

Asked By: Gus

||

Answers:

What you’re trying to achieve is possible in maybe bash and some other stringly typed languages, not in Python.

This is perhaps the closest you can do in Python.

var_name = 'bar'
var_value = 1

foo(**{var_name: var_value})
# equivalent to foo(bar=1)
Answered By: mike3996

You can use exec to evaluate the string as if it were “typed in”

def foo(bar):
    print bar

foo(bar=1)

argString = "bar=1"

foo(argString)


exec("foo(" + argString + ")")

Running this:

1
bar=1
1

However using exec/eval is generally not recommended, so if I were you I’d still try to figure out some other way.

Answered By: hoodakaushal

I think this question boils down to the difference between named and positional arguments.

Let’s define a function foo(bar):

def foo(bar):
    print(bar, "(type: " + str(type(bar)) + ")")

Now, let’s run some examples:

foo(1)
# 1 (type: <class 'int'>)

This is a positional argument, it goes into the function in the order you give it.
In this case, there is only one argument, so it goes into the first position of the foo function, which is the argument bar.

foo(bar=1)
# 1 (type: <class 'int'>)

This is the named equivalent of the previous version. Instead of feeding it into the function as the n-th argument, it explicitely feeds it into the argument named bar.

foo('bar=1')
# bar=1 (type: <class 'str'>)

This is a positional argument, with the string 'bar=1'. Python doesn’t care what the content of that string is, it is and stays the string with the content 'bar=1'.

I suspect what you are trying to do is to feed the function named arguments, but with the arguments defined in a dict-like structure. You can achieve that like this:

args = {'bar': 1}
foo(**args)
# 1 (type: <class 'int'>)

This way, the dict args gets taken as named arguments of that function.

Now back to the question you originally had, which is, how to use the string 'bar=1' to achieve the same result. I don’t think this is easily possible. It would involve parsing the string manually, then setting up that dict of named arguments. I’m not sure what you are trying to do with it, but there must surely be a better solution than using strings for that.

Answered By: Finomnis

Convert a string to a dictionary, not forgetting possible errors when casting to int:

def foo(bar = 1):
    print('bar:', type(bar), bar)

s = 'bar = 170'
d = {k.strip(): int(v.strip()) for k, v in [s.split('=', 1)]}
print('d:', type(d), d)
foo(**d)

Output:

d: <class 'dict'> {'bar': 170}
bar: <class 'int'> 170

Python has the configparse module if there is a need to work with INI files.

Answered By: Andrei Odegov

I think I get what you’re asking.

You’re not defining a function. foo() is already a function (or method or whatever) and you’re trying to use it by entering a string as the keyword argument, right?

If you are trying to define a function, Finomnis is the most helpful.

However, if foo() is an already made function and you’re trying to put a string in as the keyword argument, you can use an if statement as a lazy, hardcoded workaround.

#foo() is a function that exists already...
string = 'bar = 1'
if string == 'bar = 1':
    foo(bar=1)

Definitely not the best way, but it works. 🙂

Answered By: Nube
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.