How do I import variable packages in Python like using variable variables ($$) in PHP?

前端 未结 5 2051
暖寄归人
暖寄归人 2020-11-29 00:05

I want to import some package depending on which value the user chooses.

The default is file1.py:



        
5条回答
  •  借酒劲吻你
    2020-11-29 00:47

    Python doesn't have a feature that's directly equivalent to PHP's "variable variables". To get a "variable variable"'s value (or the value of any other expression) you can use the eval function.

    foo = "Hello World"
    print eval("foo")
    

    However, this can't be used in an import statement.

    It is possible to use the __import__ function to import using a variable.

    package = "os"
    name = "path"
    
    imported = getattr(__import__(package, fromlist=[name]), name)
    

    is equivalent to

    from os import path as imported
    

提交回复
热议问题