What is __ import __ in python?
View Discussion Show
Improve Article Save Article View Discussion Improve Article Save Article While writing a code, there might be a need for some specific modules. So we import those modules by using a single line code in Python. But
what if the name of the module needed is known to us only during runtime? How can we import that module? One can use the Python’s inbuilt
Example #1 :
Output :
New in version 3.1. Source code: Lib/importlib/__init__.py Introduction¶The purpose of
the Two, the components to implement See also The import statementThe language reference for the Original specification of packages. Some semantics have changed since the writing of this document (e.g. redirecting based on __import__() functionThe Import on Case-Insensitive Platforms PEP 263Defining Python Source Code Encodings PEP 302New Import Hooks PEP 328Imports: Multi-Line and Absolute/Relative PEP 366Main module explicit relative imports PEP 420Implicit namespace packages PEP 451A ModuleSpec Type for the Import System PEP 488Elimination of PYO files PEP 489Multi-phase extension module initialization PEP 552Deterministic pycs PEP 3120Using UTF-8 as the Default Source Encoding PEP 3147PYC Repository Directories Functions¶importlib. __import__ (name,
globals=None, locals=None, fromlist=(), level=0)¶An implementation of the built-in
Note Programmatic importing of modules should use importlib. import_module (name,
package=None)¶Import a module. The name argument specifies what module to import in absolute or relative terms (e.g. either The If you are dynamically importing a module that was created since the interpreter began execution (e.g., created a Python source file), you may need to call Changed in version 3.3: Parent packages are automatically imported. importlib. find_loader (name, path=None)¶Find the loader for a module,
optionally within the specified path. If the module is in A dotted name does not have its parents implicitly imported as that requires loading them and that may not be desired. To properly import a submodule you will need to import all parent packages of the submodule and use the correct argument to path. New in version 3.3. Changed in
version 3.4: If importlib. invalidate_caches ()¶Invalidate the internal
caches of finders stored at New in version 3.3. importlib. reload (module)¶Reload a previously imported module. The argument must be a module object, so it must have been successfully imported before. This is useful if you have edited the module source file using an external editor and want to try out the new version
without leaving the Python interpreter. The return value is the module object (which can be different if re-importing causes a different object to be placed in When
There are a number of other caveats: When a module is reloaded, its dictionary (containing the module’s global variables) is retained. Redefinitions of names will override the old definitions, so this is
generally not a problem. If the new version of a module does not define a name that was defined by the old version, the old definition remains. This feature can be used to the module’s advantage if it maintains a global table or cache of objects — with a try: cache except NameError: cache = {} It is generally not very useful to
reload built-in or dynamically loaded modules. Reloading If a module imports objects from another module using If a module instantiates instances of a class, reloading the module that defines the class does not affect the method definitions of the instances — they continue to use the old class definition. The same is true for derived classes. New in version 3.4. importlib.abc – Abstract base classes related to import¶Source code: Lib/importlib/abc.py The ABC hierarchy: object +-- Finder (deprecated) +-- MetaPathFinder +-- PathEntryFinder +-- Loader +-- ResourceLoader --------+ +-- InspectLoader | +-- ExecutionLoader --+ +-- FileLoader +-- SourceLoaderclass importlib.abc. Finder ¶
An abstract base class representing a finder. abstractmethodfind_module (fullname,
path=None)¶An abstract method for finding a loader for the specified module. Originally specified in
PEP 302, this method was meant for use in Changed in version 3.4: Returns importlib.abc. MetaPathFinder ¶An abstract base class representing a meta path finder. New in version 3.3. Changed in version 3.10: No longer a subclass of find_spec (fullname,
path, target=None)¶An abstract method for finding a spec for the specified module. If this is a top-level import, path will be New in version 3.4. find_module (fullname,
path)¶A legacy method for finding a loader for the specified module. If this is a top-level import, path will be If Changed in version 3.4:
Returns Deprecated since version 3.4: Use
invalidate_caches ()¶An optional method which, when
called, should invalidate any internal cache used by the finder. Used by Changed in version 3.4: Returns importlib.abc. PathEntryFinder ¶An abstract base class representing a path entry finder. Though it bears some similarities to
New in version 3.3. Changed in version 3.10: No longer a subclass
of find_spec (fullname, target=None)¶An
abstract method for finding a spec for the specified module. The finder will search for the module only within the path entry to which it is assigned. If a spec cannot be found, New in version 3.4. find_loader (fullname)¶A legacy method for finding a loader for the specified module. Returns a 2-tuple of If
Changed in version 3.4: Returns Deprecated since version 3.4: Use find_module (fullname)¶A concrete implementation of Deprecated since version 3.4: Use invalidate_caches ()¶An optional method which, when called, should invalidate any internal cache used by the finder. Used by importlib.abc. Loader ¶An abstract base class for a loader. See PEP 302 for the exact definition for a loader. Loaders that wish to support resource reading should implement a Changed in version 3.7: Introduced the optional create_module (spec)¶A method that returns the module object to use when importing a module. This method may return New in version 3.4. Changed in version 3.5:
Starting in Python 3.6, this method will not be optional when exec_module (module)¶An abstract method that executes the module in its own namespace when a module is imported or reloaded. The module should already be initialized when New in version 3.4. Changed in version 3.6:
load_module (fullname)¶A legacy method
for loading a module. If the module cannot be loaded, If the requested module already exists in The loader should set several attributes on the module. (Note that some of these attributes can change when a module is reloaded):
When
Deprecated since version 3.4: The recommended API for loading a module is module_repr (module)¶A legacy method which when implemented calculates and returns the given module’s repr, as a string. The module type’s default repr() will use the result of this method as appropriate. New in version 3.3. Changed in version 3.4: Made optional instead of an abstractmethod. Deprecated since version 3.4: The import machinery now takes care of this automatically. classimportlib.abc. ResourceReader ¶Superseded by TraversableResources An abstract base class to provide the ability to read resources. From the perspective of this ABC, a resource is a binary artifact that is shipped within a package. Typically this is something like a data file that lives next to the For any of methods of this class, a resource argument is expected to be a path-like object which represents conceptually just a file name. This means that no subdirectory paths should be included in the resource argument. This is because the location of the package the reader is for, acts as the “directory”. Hence the metaphor for directories and file names is packages and resources, respectively. This is also why instances of this class are expected to directly correlate to a specific package (instead of potentially representing multiple packages or a module). Loaders that wish to support resource reading are expected to provide a method called New in version 3.7. abstractmethodopen_resource (resource)¶Returns an opened, file-like object for binary reading of the resource. If the resource cannot be found,
resource_path (resource)¶Returns the file system path to the resource. If the resource does not concretely exist on the file system, raise is_resource (name)¶Returns contents ()¶Returns an iterable of strings over the contents of the package. Do note that it is not required that all names
returned by the iterator be actual resources, e.g. it is acceptable to return names for which Allowing non-resource names to be returned is to allow for situations where how a package and its resources are stored are known a priori and the non-resource names would be useful. For instance, returning subdirectory names is allowed so that when it is known that the package and resources are stored on the file system then those subdirectory names can be used directly. The abstract method returns an iterable of no items. classimportlib.abc. ResourceLoader ¶An abstract base class for a loader which implements the optional PEP 302 protocol for loading arbitrary resources from the storage back-end. Deprecated since version 3.7: This ABC is deprecated in favour of supporting resource loading through
get_data (path)¶An abstract method to return the
bytes for the data located at path. Loaders that have a file-like storage back-end that allows storing arbitrary data can implement this abstract method to give direct access to the data stored. importlib.abc. InspectLoader ¶An abstract base class for a loader which implements the optional PEP 302 protocol for loaders that inspect modules. get_code (fullname)¶Return the code object for a module, or Note While the method has a default implementation, it is suggested that it be overridden if possible for performance. Changed in version 3.4: No longer abstract and a concrete implementation is provided. abstractmethodget_source (fullname)¶An abstract method to return the source of a module. It is returned as a text string using universal newlines, translating all recognized line separators
into is_package (fullname)¶An optional method to return a true value if the module is a package, a false value otherwise. source_to_code (data, path='Create a code object from Python source. The data argument can be whatever the With the subsequent code object one can execute it in a module by running New in version 3.4. Changed in version 3.5: Made the method static. exec_module (module)¶Implementation of New in version 3.4. load_module (fullname)¶Implementation of Deprecated since version
3.4: use importlib.abc. ExecutionLoader ¶An abstract base class which inherits from
get_filename (fullname)¶An abstract method that is to return the value of If source code is available, then the method should return the path to the source file, regardless of whether a bytecode was used to load the module. classimportlib.abc. FileLoader (fullname,
path)¶An abstract base class which inherits from The fullname argument is a fully resolved name of the module the loader is to handle. The path argument is the path to the file for the module. New in version 3.3. name ¶The name of the module the loader can handle. path ¶Path to the file of the module. load_module (fullname)¶
Calls super’s get_filename (fullname)¶Returns
get_data (path)¶Reads path as a binary file and returns the bytes from it. classimportlib.abc. SourceLoader ¶An abstract base class for implementing source (and optionally bytecode) file loading. The class inherits from both
The
abstract methods defined by this class are to add optional bytecode file support. Not implementing these optional methods (or causing them to raise path_stats (path)¶Optional abstract method which returns a
Any other keys in the dictionary are ignored, to allow for future extensions. If the path cannot be
handled, New in version 3.3. path_mtime (path)¶Optional abstract method which returns the modification time for the specified path. Deprecated since version 3.3: This method is deprecated in favour of set_data (path, data)¶Optional abstract method which writes the specified bytes to a file path. Any intermediate directories which do not exist are to be created automatically. When writing to the path fails because the path is read-only ( get_code (fullname)¶Concrete implementation of exec_module (module)¶Concrete implementation of New in version 3.4. load_module (fullname)¶Concrete implementation of
Deprecated since version 3.4: Use get_source (fullname)¶Concrete implementation of is_package (fullname)¶Concrete implementation of importlib.abc. Traversable ¶An object with a subset of pathlib.Path methods suitable for traversing directories and opening files. New in version 3.9. abstractmethodname ()¶The base name of this object without any parent references. iterdir ()¶Yield Traversable objects in self. abstractmethodis_dir ()¶Return True if self is a directory. abstractmethodis_file ()¶Return True if self is a file. abstractmethodjoinpath (child)¶Return Traversable child in self. abstractmethod__truediv__ (child)¶Return Traversable child in self. abstractmethodopen (mode='r', *args,
**kwargs)¶mode may be ‘r’ or ‘rb’ to open as text or binary. Return a handle suitable for reading (same as When opening as text, accepts encoding
parameters such as those accepted by read_bytes ()¶Read contents of self as bytes. read_text (encoding=None)¶Read contents of self as text. classimportlib.abc. TraversableResources ¶An abstract base class for resource readers capable of serving the Loaders that wish to support resource reading are expected to implement this interface. New in version 3.9. importlib.resources – Resources¶Source code: Lib/importlib/resources.py New in version 3.7. This module leverages Python’s import system to provide access to resources within packages. If you can import a package, you can access resources within that package. Resources can be opened or read, in either binary or text mode. Resources are roughly akin to files inside directories, though it’s important to keep in mind that this is just a metaphor. Resources and packages do not have to exist as physical files and directories on the file system. Loaders that wish to support resource reading should implement a The following types are defined. importlib.resources. Package ¶The importlib.resources. Resource ¶This type describes the resource names passed into the various functions in this package. This is defined as The following functions are available. importlib.resources. files (package)¶Returns an package is either a name or a module object which conforms to the New in version 3.9. importlib.resources. as_file (traversable)¶Given a Exiting the context manager cleans up any temporary file created when the resource was extracted from e.g. a zip file. Use New in version 3.9. importlib.resources. open_binary (package,
resource)¶Open for binary reading the resource within package. package is either a name or a module object which conforms to the importlib.resources. open_text (package, resource, encoding='utf-8',
errors='strict')¶Open for text reading the resource within package. By default, the resource is opened for reading as UTF-8. package is either a name or a module object which conforms to the This function returns a importlib.resources. read_binary (package, resource)¶Read and return the contents of the resource within package as package is either a name or a module object which conforms to the importlib.resources. read_text (package,
resource, encoding='utf-8', errors='strict')¶Read and return the contents of resource within package as a package is
either a name or a module object which conforms to the importlib.resources. path (package, resource)¶Return the path to the resource as an actual file system path. This function
returns a context manager for use in a Exiting the context manager cleans up any temporary file created when the resource needs to be extracted from e.g. a zip file. package is either a name or a module object
which conforms to the importlib.resources. is_resource (package,
name)¶Return importlib.resources. contents (package)¶Return an iterable over the named items within the package. The iterable returns package is either a name or a module object which conforms to the importlib.machinery – Importers and path hooks¶Source code: Lib/importlib/machinery.py This module contains the various objects that help importlib.machinery. SOURCE_SUFFIXES ¶A list of strings representing the recognized file suffixes for source modules. New in version 3.3. importlib.machinery. DEBUG_BYTECODE_SUFFIXES ¶A list of strings representing the file suffixes for non-optimized bytecode modules. New in version 3.3. importlib.machinery. OPTIMIZED_BYTECODE_SUFFIXES ¶A list of strings representing the file suffixes for optimized bytecode modules. New in version 3.3. importlib.machinery. BYTECODE_SUFFIXES ¶A list of strings representing the recognized file suffixes for bytecode modules (including the leading dot). New in version 3.3. Changed in version 3.5: The value is no longer dependent on importlib.machinery. EXTENSION_SUFFIXES ¶A list of strings representing the recognized file suffixes for extension modules. New in version 3.3. importlib.machinery. all_suffixes ()¶Returns a combined list of strings representing all file suffixes for modules recognized by the standard import machinery. This is a helper for code which simply needs to know if a filesystem path potentially refers to a module without needing any
details on the kind of module (for example, New in version 3.3. classimportlib.machinery. BuiltinImporter ¶An
importer for built-in modules. All known built-in modules are listed in Only class methods are defined by this class to alleviate the need for instantiation. Changed in version 3.5: As part of PEP 489, the builtin importer now implements importlib.machinery. FrozenImporter ¶An importer for frozen modules. This class implements the
Only class methods are defined by this class to alleviate the need for instantiation. Changed in version 3.4: Gained importlib.machinery. WindowsRegistryFinder ¶Finder for modules declared in the Windows registry. This class implements the
Only class methods are defined by this class to alleviate the need for instantiation. New in version 3.3. Deprecated since version 3.6: Use
importlib.machinery. PathFinder ¶A Finder for Only class methods are defined by this class to alleviate the need for instantiation. classmethodfind_spec (fullname, path=None,
target=None)¶Class method that attempts to find a spec for the module specified by fullname on
New in version 3.4. Changed in version 3.5: If the current working directory – represented by an empty string – is no longer valid then find_module (fullname,
path=None)¶A legacy wrapper around Deprecated since version 3.4: Use
invalidate_caches ()¶Calls
Changed in version 3.4: Calls objects in importlib.machinery. FileFinder (path, *loader_details)¶A concrete implementation of The path argument is the directory for which the finder is in charge of searching. The loader_details argument is a variable number of 2-item tuples each containing a loader and a sequence of file suffixes the loader recognizes. The loaders are expected to be callables which accept two arguments of the module’s name and the path to the file found. The finder will cache the directory contents as necessary, making stat calls for each module
search to verify the cache is not outdated. Because cache staleness relies upon the granularity of the operating system’s state information of the file system, there is a potential race condition of searching for a module, creating a new file, and then searching for the module the new file represents. If the operations happen fast enough to fit within the granularity of stat calls, then the module search will fail. To prevent this from happening, when you create a module dynamically, make sure
to call New in version 3.3. path ¶The path the finder will search in. find_spec (fullname, target=None)¶Attempt to find the spec to handle fullname within
New in version 3.4. find_loader (fullname)¶Attempt to find the loader to handle fullname within Deprecated
since version 3.10: Use invalidate_caches ()¶
Clear out the internal cache. classmethodpath_hook (*loader_details)¶A class method which returns a closure for use on
If the argument to the closure is not an existing directory,
importlib.machinery. SourceFileLoader (fullname, path)¶A concrete
implementation of New in version 3.3. name ¶The name of the module that this loader will handle. path ¶The path to the source file. is_package (fullname)¶Return path_stats (path)¶Concrete implementation of set_data (path, data)¶Concrete implementation of
load_module (name=None)¶Concrete implementation of importlib.machinery. SourcelessFileLoader (fullname, path)¶A concrete implementation of
Please note that direct use of bytecode files (and thus not source code files) inhibits your modules from being usable by all Python implementations or new versions of Python which change the bytecode format. New in version 3.3. name ¶The name of the module the loader will handle. path ¶The path to the bytecode file. is_package (fullname)¶Determines if the module is a package based on get_code (fullname)¶Returns the code object for
get_source (fullname)¶Returns load_module (name=None)¶Concrete implementation of importlib.machinery. ExtensionFileLoader (fullname, path)¶A concrete implementation of
The fullname argument specifies the name of the module the loader is to support. The path argument is the path to the extension module’s file. New in version 3.3. name ¶Name of the module the loader supports. path ¶Path to the extension module. create_module (spec)¶Creates the module object from the given specification in accordance with PEP 489. New in version 3.5. exec_module (module)¶Initializes the given module object in accordance with PEP 489. New in version 3.5. is_package (fullname)¶Returns get_code (fullname)¶Returns
get_source (fullname)¶Returns get_filename (fullname)¶Returns
New in version 3.4. classimportlib.machinery. ModuleSpec (name, loader, *,
origin=None, loader_state=None, is_package=None)¶A specification for a module’s import-system-related state. This is typically exposed as the module’s New in version 3.4. name ¶( A string for the fully qualified name of the module. loader ¶
( The Loader that should be used when loading the module. Finders should always set this. origin ¶( Name of the place from which the module is loaded, e.g. “builtin” for built-in modules and the filename for modules loaded from source. Normally “origin” should be set, but it may be submodule_search_locations ¶( List of strings for where to find submodules, if a package ( loader_state ¶Container of extra module-specific data for use during loading (or cached ¶( String for where the compiled module should be stored (or parent ¶
( (Read-only) The fully qualified name of the package under which the module should be loaded as a submodule (or the empty string for top-level modules). For packages, it is the same as has_location ¶Boolean indicating whether or not the module’s “origin” attribute refers to a loadable location. importlib.util – Utility code for importers¶Source code: Lib/importlib/util.py This module contains the various objects that help in the construction of an importer. importlib.util. MAGIC_NUMBER ¶The bytes which represent the bytecode version number. If you need help with loading/writing bytecode then
consider New in version 3.4. importlib.util. cache_from_source (path, debug_override=None, *,
optimization=None)¶Return the PEP 3147/PEP 488
path to the byte-compiled file associated with the source path. For example, if path is The optimization parameter is used to specify the optimization
level of the bytecode file. An empty string represents no optimization, so The debug_override parameter is deprecated and can be used to override the system’s value for New in version 3.4. Changed in version 3.5: The optimization parameter was added and the debug_override parameter was deprecated. importlib.util. source_from_cache (path)¶Given the path to a PEP 3147 file name, return the associated source code file path. For example, if
path is New in version 3.4. importlib.util. decode_source (source_bytes)¶Decode the given bytes representing source code and return it as a string with universal newlines (as required by
New in version 3.4. importlib.util. resolve_name (name, package)¶Resolve a relative module name to an absolute one. If name has no leading dots, then name is simply returned. This allows for usage such as
New in version 3.3. Changed in version 3.9: To improve consistency with import statements, raise
importlib.util. find_spec (name,
package=None)¶Find the spec for a module, optionally relative to the specified package name. If the module is in
If name is for a submodule (contains a dot), the parent module is automatically imported. name and package work the same as for New in version 3.4. importlib.util. module_from_spec (spec)¶Create a new module based on spec and If
This
function is preferred over using New in version 3.5. @ importlib.util. module_for_loader ¶A decorator for
The decorated method will take in the name of the module to be loaded as expected for a loader. If the module is not found in If an exception is raised by the decorated method and a module was added to Changed in version 3.3: Deprecated since version 3.4: The import machinery now directly performs all the functionality provided by this function. @ importlib.util. set_loader ¶A decorator for
Changed in version 3.4: Set Deprecated since version 3.4: The import machinery takes care of this automatically. @ importlib.util. set_package ¶A decorator for Deprecated since version 3.4: The import machinery takes care of this automatically. importlib.util. spec_from_loader (name, loader, *, origin=None, is_package=None)¶A factory function for creating a
New in version 3.4. importlib.util. spec_from_file_location (name, location, *, loader=None, submodule_search_locations=None)¶A
factory function for creating a New in version 3.4. importlib.util. source_hash (source_bytes)¶Return the hash of source_bytes as bytes. A hash-based New in version 3.7. classimportlib.util. LazyLoader (loader)¶A class which postpones the execution of the loader of a module until the module has an attribute accessed. This class only works with loaders that define
Note For projects where startup time is critical, this class allows for potentially minimizing the cost of loading a module if it is never used. For projects where startup time is not essential then use of this class is heavily discouraged due to error messages created during loading being postponed and thus occurring out of context. New in version 3.5. classmethodfactory (loader)¶A static method which returns a callable that creates a lazy loader. This is meant to be used in situations where the loader is passed by class instead of by instance. suffixes = importlib.machinery.SOURCE_SUFFIXES loader = importlib.machinery.SourceFileLoader lazy_loader = importlib.util.LazyLoader.factory(loader) finder = importlib.machinery.FileFinder(path, (lazy_loader, suffixes)) Examples¶Importing programmatically¶To programmatically import a module, use import importlib itertools = importlib.import_module('itertools') Checking if a module can be imported¶If you need to find out if a module can be imported without actually doing the import, then you should use Note that if import importlib.util import sys # For illustrative purposes. name = 'itertools' if name in sys.modules: print(f"{name!r} already in sys.modules") elif (spec := importlib.util.find_spec(name)) is not None: # If you chose to perform the actual import ... module = importlib.util.module_from_spec(spec) sys.modules[name] = module spec.loader.exec_module(module) print(f"{name!r} has been imported") else: print(f"can't find the {name!r} module") Importing a source file directly¶To import a Python source file directly, use the following recipe (Python 3.5 and newer only): import importlib.util import sys # For illustrative purposes. import tokenize file_path = tokenize.__file__ module_name = tokenize.__name__ spec = importlib.util.spec_from_file_location(module_name, file_path) module = importlib.util.module_from_spec(spec) sys.modules[module_name] = module spec.loader.exec_module(module) Implementing lazy imports¶The example below shows how to implement lazy imports: >>> import importlib.util >>> import sys >>> def lazy_import(name): ... spec = importlib.util.find_spec(name) ... loader = importlib.util.LazyLoader(spec.loader) ... spec.loader = loader ... module = importlib.util.module_from_spec(spec) ... sys.modules[name] = module ... loader.exec_module(module) ... return module ... >>> lazy_typing = lazy_import("typing") >>> #lazy_typing is a real module object, >>> #but it is not loaded in memory yet. >>> lazy_typing.TYPE_CHECKING False Setting up an importer¶For deep customizations of import, you typically want to implement an importer. This means managing both the finder and
loader side of things. For finders there are two flavours to choose from depending on your needs: a meta path finder or a path entry finder. The former is what you would put on
import importlib.machinery import sys # For illustrative purposes only. SpamMetaPathFinder = importlib.machinery.PathFinder SpamPathEntryFinder = importlib.machinery.FileFinder loader_details = (importlib.machinery.SourceFileLoader, importlib.machinery.SOURCE_SUFFIXES) # Setting up a meta path finder. # Make sure to put the finder in the proper location in the list in terms of # priority. sys.meta_path.append(SpamMetaPathFinder) # Setting up a path entry finder. # Make sure to put the path hook in the proper location in the list in terms # of priority. sys.path_hooks.append(SpamPathEntryFinder.path_hook(loader_details)) Approximating importlib.import_module()¶Import itself is implemented in Python code, making it possible to expose most of the import machinery through importlib. The following helps illustrate the various APIs that importlib exposes by
providing an approximate implementation of import importlib.util import sys def import_module(name, package=None): """An approximate implementation of import.""" absolute_name = importlib.util.resolve_name(name, package) try: return sys.modules[absolute_name] except KeyError: pass path = None if '.' in absolute_name: parent_name, _, child_name = absolute_name.rpartition('.') parent_module = import_module(parent_name) path = parent_module.__spec__.submodule_search_locations for finder in sys.meta_path: spec = finder.find_spec(absolute_name, path) if spec is not None: break else: msg = f'No module named {absolute_name!r}' raise ModuleNotFoundError(msg, name=absolute_name) module = importlib.util.module_from_spec(spec) sys.modules[absolute_name] = module spec.loader.exec_module(module) if path is not None: setattr(parent_module, child_name, module) return module What is __ name __ Python?In Python, the special name __main__ is used for two important constructs: the name of the top-level environment of the program, which can be checked using the __name__ == '__main__' expression; and. the __main__.py file in Python packages.
What is the use of __ main __ in Python?Python includes the special variable called __name__ that contains the scope of the code being executed as a string. __main__ is the name of the top-level scope in which top-level code executes. For example, the scope of the code executed in the interpreter shell will be __main__ , as shown below.
What is __ module __ in Python?A module in Python is a file (ending in .py ) that contains a set of definitions (variables and functions) that you can use when they are imported. Modules are considered as objects, just as everything else is in Python.
What is __ spec __ Python?The __spec__ attribute must be set to the module spec that was used when importing the module. This is used primarily for introspection and during reloading. Setting __spec__ appropriately applies equally to modules initialized during interpreter startup.
|