Wednesday, 14 December 2016

How to import other Python files?



How do I import other files in Python?





  1. How exactly can I import a specific python file like import file.py?

  2. How can I import a folder instead of a specific file?

  3. I want to load a Python file dynamically at runtime, based on user
    input.

  4. I want to know how to load just one specific part from the file.



For example, in main.py I have:




from extra import * 


Although this gives me all the definitions in extra.py, when maybe all I want is a single definition:



def gap():
print
print



What do I add to the import statement to just get gap from extra.py?


Answer



importlib is recent addition in Python to programmatically import a module. It just a wrapper around __import__
See https://docs.python.org/3/library/importlib.html#module-importlib



import importlib

moduleName = input('Enter module name:')
importlib.import_module(moduleName)






Update: Answer below is outdated. Use the more recent alternative above.




  1. Just import file without the '.py' extension.


  2. You can mark a folder as a package, by adding an empty file named __init__.py.


  3. You can use the __import__ function. It takes the module name as a string. (Again: module name without the '.py' extension.)




    pmName = input('Enter module name:')
    pm = __import__(pmName)
    print(dir(pm))


    Type help(__import__) for more details.



No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...