Gus
Gus

Reputation: 171

Use string as function arguments

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.

Upvotes: 0

Views: 2455

Answers (6)

Wayfarer
Wayfarer

Reputation: 1

Too late to answer the original question, but may be usefull for those who googled this. There's a weird, though working way to do what needed.

def args_to_dict(**kwargs):
    global dict_params
    dict_params = locals()["kwargs"]

def str_to_dict_args(s):
    code = f"args_to_dict({s})" 
    exec(code)
    return dict_params

test_args = "a=5, c='10', d=20"
str_to_dict_args(test_args)
>>> {'a': 5, 'c': '10', 'd': 20}

This sample converts arguments string to kwargs dict that can be used later.

Upvotes: 0

Nube
Nube

Reputation: 1

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. :)

Upvotes: 0

Andrei Odegov
Andrei Odegov

Reputation: 3439

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.

Upvotes: 0

Finomnis
Finomnis

Reputation: 22838

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.

Upvotes: 3

hoodakaushal
hoodakaushal

Reputation: 1293

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.

Upvotes: -1

mike3996
mike3996

Reputation: 17537

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)

Upvotes: 0

Related Questions