Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does python find a module file if the import statement only contains the filename?

Everywhere I see Python code importing modules using import sys or import mymodule

How does the interpreter find the correct file if no directory or path is provided?

like image 652
Asciiom Avatar asked Mar 06 '13 15:03

Asciiom


People also ask

How does Python know where to look for the modules and packages that are imported?

It uses the PYTHONPATH, set as an environment variable, to find packages (folders containing __init__.py files) and modules (or, if already loaded once, retrieves the module object from sys. modules ).

What Python does when it sees an import statement?

The Python import statement lets you import a module into your code. A module is a file that contains functions and values that you can reference from your program. The import statement syntax is: import modulename.

What happens when a module is imported in Python?

When a module is first imported, Python searches for the module and if found, it creates a module object 1, initializing it. If the named module cannot be found, a ModuleNotFoundError is raised. Python implements various strategies to search for the named module when the import machinery is invoked.


1 Answers

http://docs.python.org/3/tutorial/modules.html#the-module-search-path

6.1.2. The Module Search Path

When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path. sys.path is initialized from these locations:

  • The directory containing the input script (or the current directory when no file is specified).
  • PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
  • The installation-dependent default.

Note: On file systems which support symlinks, the directory containing the input script is calculated after the symlink is followed. In other words the directory containing the symlink is not added to the module search path.

After initialization, Python programs can modify sys.path. The directory containing the script being run is placed at the beginning of the search path, ahead of the standard library path. This means that scripts in that directory will be loaded instead of modules of the same name in the library directory. This is an error unless the replacement is intended. See section Standard Modules for more information.

For information on the "installation-specific default", see documentation on the site module.

like image 79
dm03514 Avatar answered Sep 23 '22 15:09

dm03514