0

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 Jun 9, 2019 at 7:06
1
  • 1
    What's your exact question? From what I see, everything is intended behaviour. You create a string with the content 'bar = 1', and when you put it in a function, it still is a string, why should it be anything else. You should look up the difference between named and positional arguments. Commented Jun 9, 2019 at 7:09

6 Answers 6

3

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 Jun 9, 2019 at 7:20
Sign up to request clarification or add additional context in comments.

Comments

0

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 Jun 9, 2019 at 7:12

Comments

0

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 Jun 9, 2019 at 8:52

Comments

0

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 Dec 20, 2022 at 6:23

Comments

0

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.

answered Aug 23, 2023 at 8:50

Comments

-1

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 Jun 9, 2019 at 7:14

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.