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

前端 未结 5 2050
暖寄归人
暖寄归人 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 01:00

    Basing myself on mattjbray's answer:

    from importlib import import_module
    
    # lookup in a set is in constant time
    safe_names = {"file1.py", "file2.py", "file3.py", ...}
    
    user_input = ...
    
    if user_input in safe_names:
        file = import_module(user_input)
    else:
        print("Nope, not doing this.")
    

    Saves a few lines of code, and allows you to set safe_names programmatically, or load multiple modules and assign them to a dict, for example.

提交回复
热议问题