C
C
Coder 14482020-06-11 16:06:15
Python
Coder 1448, 2020-06-11 16:06:15

How to call a variable with string data type?

The user enters a function, and then I work with it. Python treats the value "y" as a dumb string, not something you can work with.

y = input( ‘Введите функцию’ )
x = input( ‘Введите аргумент (x)’ )
answer = y(x)

Error: TypeError: type 'str' can't be called.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
Rais, 2020-06-11
@wows15

exec (y + '("' + str(x) + '")')
But it's dangerous to do so

S
ScriptKiddo, 2020-06-11
@ScriptKiddo

You need to get the function by name

import sys

this_module = sys.modules[__name__]


def square(x):
    return x * x


print(getattr(this_module, 'square')(10))

OUT

Foo

Process finished with exit code 0


Source: https://stackoverflow.com/a/2933481
Or do like this
def square(x):
    return x * x


functions = {
    'square': square
}

print(functions['square'](10))

OUT

100

Process finished with exit code 0

G
galaxy, 2020-06-11
@galaxy

If the function is defined in your script: locals()[y](x)
You can also call built-in functions: locals()['__builtins__'][y](x)
That shitty code, of course..

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question