Search code examples
pythonevalpython-importlib

Get function from string containing the full name


I have a string like:

str = "pwd.getpwuid(1000)"

Now, if I try to eval() that it may raise an exception because I have not import pwd yet (or maybe not if I have).

So I decided to write a parser that: splits that string on "." and get a list:

lis = ["pwd", "getpwuid(1000)"]

then take lis[0], if it does not contain "(" or ")" I call

importlib.import_module(lis[0])

and then again the eval.

Can I make the same thing better?


Solution

  • Found a solution:

    I must change the strings to contains body of functions:

    str = "(lambda x: __import__('pwd').getpwuid(x))(1000)"
    

    eval() on this is ok!

    (lambda or def obviously are the same)