In python there is no restriction on the name of a module file.
Python code in one module gains access to the code in another module by the process of importing it. The Show
The
A direct call to When an 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
Changed in version 3.3: The import system has been updated to fully implement the second phase of
PEP 302. There is no longer any implicit import machinery - the full import system is exposed through 5.1. importlib¶The 5.2. Packages¶Python has only one type of module object, and all modules are of this type, regardless of whether the module is implemented in Python, C, or something else. To help organize modules and provide a naming hierarchy, Python has a concept of packages. You can think of packages as the directories on a file system and modules as files within directories, but don’t take this analogy too literally since packages and modules need not originate from the file system. For the purposes of this documentation, we’ll use this convenient analogy of directories and files. Like file system directories, packages are organized hierarchically, and packages may themselves contain subpackages, as well as regular modules. It’s important to keep in mind that all packages are modules, but not all modules are packages. Or put another way, packages are just a special kind of module. Specifically, any module that contains a All
modules have a name. Subpackage names are separated from their parent package name by a dot, akin to Python’s standard attribute access syntax. Thus you might have a package called 5.2.1. Regular packages¶Python defines two types of packages,
regular packages and namespace packages. Regular packages are traditional packages as they existed in Python 3.2 and earlier. A regular package is typically implemented as a directory containing an For example, the following file system layout defines a top level parent/ __init__.py one/ __init__.py two/ __init__.py three/ __init__.py Importing 5.2.2. Namespace packages¶A namespace package is a composite of various portions, where each portion contributes a subpackage to the parent package. Portions may reside in different locations on the file system. Portions may also be found in zip files, on the network, or anywhere else that Python searches during import. Namespace packages may or may not correspond directly to objects on the file system; they may be virtual modules that have no concrete representation. Namespace packages do not use an ordinary list for their With namespace packages, there is no See also PEP 420 for the namespace package specification. 5.3. Searching¶To begin the search, Python needs the fully qualified name of the module (or package, but for the purposes of this discussion, the difference is immaterial) being imported. This name may come from various arguments to the
This name will be used in various phases of the import search, and it may be
the dotted path to a submodule, e.g. 5.3.1. The module cache¶The first place checked during import search is During import, the module name is looked up in
Beware though, as if you keep a reference to the module object, invalidate its cache entry in
5.3.2. Finders and loaders¶If the named module is not found in Python includes a number of default finders and importers. The first one knows how to locate built-in modules, and the second knows how to locate frozen modules. A third default finder searches an import path for modules. The import path is a list of locations that may name file system paths or zip files. It can also be extended to search for any locatable resource, such as those identified by URLs. The import machinery is extensible, so new finders can be added to extend the range and scope of module searching. Finders do not actually load modules. If they can find the named module, they return a module spec, an encapsulation of the module’s import-related information, which the import machinery then uses when loading the module. The following sections describe the protocol for finders and loaders in more detail, including how you can create and register new ones to extend the import machinery. Changed in version 3.4: In previous versions of Python, finders returned loaders directly, whereas now they return module specs which contain loaders. Loaders are still used during import but have fewer responsibilities. 5.3.3. Import hooks¶The import machinery is designed to be extensible; the primary mechanism for this are the import hooks. There are two types of import hooks: meta hooks and import path hooks. Meta hooks are called at the start of import processing, before any other import processing has occurred, other than Import path hooks are called as part of
5.3.4. The meta path¶When the named module is not found in If the meta path finder knows how to handle the named module, it returns a spec object. If it cannot handle the named module, it returns The The meta path may be traversed multiple times for a single import request. For example, assuming none of the modules involved has already been cached, importing Some meta path finders only support top level imports. These importers will always return Python’s default Changed in version 3.4: The 5.4. Loading¶If and when a module spec is found, the import machinery will use it (and the loader it contains) when loading the module. Here is an approximation of what happens during the loading portion of import: module = None if spec.loader is not None and hasattr(spec.loader, 'create_module'): # It is assumed 'exec_module' will also be defined on the loader. module = spec.loader.create_module(spec) if module is None: module = ModuleType(spec.name) # The import-related module attributes get set here: _init_module_attrs(spec, module) if spec.loader is None: # unsupported raise ImportError if spec.origin is None and spec.submodule_search_locations is not None: # namespace package sys.modules[spec.name] = module elif not hasattr(spec.loader, 'exec_module'): module = spec.loader.load_module(spec.name) # Set __loader__ and __package__ if missing. else: sys.modules[spec.name] = module try: spec.loader.exec_module(module) except BaseException: try: del sys.modules[spec.name] except KeyError: pass raise return sys.modules[spec.name] Note the following details:
Changed in version 3.4: The import system has taken over the boilerplate responsibilities of loaders. These were previously performed by the
5.4.1. Loaders¶Module loaders provide the critical function of loading: module execution. The import
machinery calls the Loaders must satisfy the following requirements:
In many cases, the finder and loader can be the same object; in such cases the Module loaders may opt in to creating the module object during loading by implementing a Changed in version 3.4: The For compatibility with existing loaders, the import machinery will use the The
Changed in version 3.5: A
Changed in version 3.6: An Changed in version 3.10: Use of 5.4.2. Submodules¶When a submodule is loaded using any mechanism (e.g. and then executing the following puts name bindings for >>> import spam >>> spam.foo Given Python’s familiar name binding rules this might seem surprising, but
it’s actually a fundamental feature of the import system. The invariant holding is that if you have 5.4.3. Module spec¶The import machinery uses a variety of information about each module during import, especially before loading. Most of the information is common to all modules. The purpose of a module’s spec is to encapsulate this import-related information on a per-module basis. Using a spec during import allows state to be transferred between import system components, e.g. between the finder that creates the module spec and the loader that executes it. Most importantly, it allows the import machinery to perform the boilerplate operations of loading, whereas without a module spec the loader had that responsibility. The module’s spec is exposed as the New in version 3.4. 5.4.5. module.__path__¶By definition, if a module has a A package’s
A package’s 5.4.6. Module reprs¶By default, all modules have a usable repr, however depending on the attributes set above, and in the module’s spec, you can more explicitly control the repr of module objects. If the module has a spec ( Here are the exact rules used:
Changed in version 3.4: Use of For backward compatibility with Python 3.3, the module repr will be generated by calling the loader’s Changed in
version 3.10: Calling 5.4.7. Cached bytecode invalidation¶Before Python loads cached bytecode from a Python also supports “hash-based” cache files, which store a hash of the source file’s contents rather than its metadata. There are two variants of hash-based Changed in
version 3.7: Added hash-based 5.5. The Path Based Finder¶As mentioned previously, Python comes with several default meta path finders. One of these, called the
path based finder ( The path based finder itself doesn’t know how to import anything. Instead, it traverses the individual path entries, associating each of them with a path entry finder that knows how to handle that particular kind of path. The default set of path entry finders implement all the semantics for finding modules on the file
system, handling special file types such as Python source code ( Path entries need not be limited to file system locations. They can refer to URLs, database queries, or any other location that can be specified as a string. The path based finder provides additional hooks and protocols so that you can extend and customize the types of searchable path entries. For example, if you wanted to support path entries as network URLs, you could write a hook that implements HTTP semantics to find modules on the web. This hook (a callable) would return a path entry finder supporting the protocol described below, which was then used to get a loader for the module from the web. A word of warning: this section and the previous both use the term finder, distinguishing between them by using the terms meta path finder
and path entry finder. These two types of finders are very similar, support similar protocols, and function in similar ways during the import process, but it’s important to keep in mind that they are subtly different. In particular, meta path finders operate at the beginning of the import process, as keyed off the
By contrast, path entry finders are in a sense an implementation detail of the path based finder, and in fact, if the path based finder were to be removed from 5.5.1. Path entry finders¶The path based finder is responsible for finding and loading Python modules and packages whose location is specified with a string path entry. Most path entries name locations in the file system, but they need not be limited to this. As a meta path finder, the path based finder implements the
Three variables are used by the
path based finder,
The path based finder is a meta path finder, so the import machinery begins the
import path search by calling the path based finder’s The path based finder iterates over every entry in the search path, and for each of these, looks for an appropriate path entry finder ( If the path entry is not present in the cache, the path based finder iterates over every callable in If If a path entry finder is returned by one of the path entry hook callables on
The current working directory – denoted by an empty string – is handled slightly differently from other entries on 5.5.2. Path entry finder protocol¶In order to support imports of modules and initialized packages and also to contribute portions to namespace packages, path entry finders must implement the
To indicate to the import machinery that the spec represents a namespace portion, the path entry finder sets “submodule_search_locations” to a list containing the portion. Changed in version 3.4: Older path entry finders may implement one of
these two deprecated methods instead of
For backwards compatibility with other implementations of the import protocol, many path entry finders also support the same, traditional The 5.6. Replacing the standard import system¶The most reliable mechanism for replacing the entire import system is to delete the default contents of If it is acceptable to only alter the behaviour of
import statements without affecting other APIs that access the import system, then replacing the builtin To selectively prevent the import of some modules from a hook early on the meta path (rather than disabling the standard
import system entirely), it is sufficient to raise 5.7. Package Relative Imports¶Relative imports use leading dots. A single leading dot indicates a relative import, starting with the current package. Two or more leading dots indicate a relative import to the parent(s) of the current package, one level per dot after the first. For example, given the following package layout: package/ __init__.py subpackage1/ __init__.py moduleX.py moduleY.py subpackage2/ __init__.py moduleZ.py moduleA.py In either from .moduleY import spam from .moduleY import spam as ham from . import moduleY from ..subpackage1 import moduleY from ..subpackage2.moduleZ import eggs from ..moduleA import foo Absolute imports may use either the should expose 5.8. Special considerations for __main__¶The 5.8.1. __main__.__spec__¶Depending on how When
Python is started with the In
the remaining cases
Note that Note also that even when 5.9. References¶The import machinery has evolved considerably since Python’s early days. The original specification for packages is still available to read, although some details have changed since the writing of that document. The original specification for PEP 420 introduced namespace packages for Python 3.3.
PEP 420 also introduced the PEP 366 describes the addition of the PEP 328 introduced absolute and explicit relative imports and initially proposed PEP 338 defines executing modules as scripts. PEP 451 adds the encapsulation of per-module import state in spec objects. It also off-loads most of the boilerplate responsibilities of loaders back onto the import machinery. These changes allow the deprecation of several APIs in the import system and also addition of new methods to finders and loaders. Footnotes 1See The importlib implementation avoids using the return value directly. Instead, it gets the module object by looking the module name up in In legacy code, it is possible to find instances of What are the rules for naming a function in Python?Method name in Python. Use only lowercase in method names.. An underscore should separate words in a method name.. Non-public method name should begin with a single underscore.. Use two consecutive underscores at the beginning of a method name, if it needs to be mangled.. Can different functions have local variables with the same name?You can have local variables with the same name in different functions, because local variables are only recognized by the function in which they are declared.
When a function is called by its name during the execution of a program it is?When a function is called by its name during the execution of a program, then it is. executed.
What is global statement in Python?What Is the Global Variable In Python? In the programming world, a global variable in Python means having a scope throughout the program, i.e., a global variable value is accessible throughout the program unless shadowed. A global variable in Python is often declared as the top of the program.
|