Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python exec takes no kwargs

help(exec)

Gives me

Help on built-in function exec in module builtins:

exec(source, globals=None, locals=None, /)
    Execute the given source in the context of globals and locals.

    The source may be a string representing one or more Python statements
    or a code object as returned by compile().
    The globals must be a dictionary and locals can be any mapping,
    defaulting to the current globals and locals.
    If only globals is given, locals defaults to it.

Though

>>> exec("print(a)", globals={'a':1})

gives me

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: exec() takes no keyword arguments

How should I pass additional arguments to the python exec function?

like image 942
Hugo Trentesaux Avatar asked Jan 21 '26 08:01

Hugo Trentesaux


2 Answers

globals() is a function that stores all information related to the global scope variables of the program. (Global symbol table)

An approach to address your requirement is as follows:

In [1]: a = 1
In [2]: exec("print(a)", globals())
        1

Or if you want to use kwargs, then it should be a function as follows:

In [1]: def val_a():
...:     return 10

In [2]: exec("print(a)", {'a': val_a()})
        10
like image 155
rkatkam Avatar answered Jan 23 '26 22:01

rkatkam


As mentioned by @juanpa.arrivillaga in comment, this is a positional argument :

exec("print(a)", {'a':1})

returns

1
like image 21
Hugo Trentesaux Avatar answered Jan 23 '26 22:01

Hugo Trentesaux



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!