What Is the Import Command in Python? Examples, Tricks, and Tips

Introduction 

We all know that Python code is more concise and reliable than other languages. But Python is more capable than you might realize. Python offers a variety of shortcuts and techniques that can be used to speed up code execution while also improving the codebase’s accuracy, such as an import command in Python. 

This article will discuss tips and tricks that you may immediately use for your Python project. It will also help you stand out from the crowd because most of the tactics aren’t always employed by inexperienced programmers. 

Basic Python Import Command 

Both packages and modules are used to structure the code in Python. In this section, we’ll go through their differences and how to work with them. 

You’ll see some complex and uncommon applications of Python’s import system later on in the article. But let’s begin with the fundamentals: importing modules and packages. 

Modules: In Python, a file is regarded as a module. The module must be imported using the import command in Python. The function or variables existing in the file is utilized in another file by importing the module. Other languages, such as typescript, JavaScript, java, ruby, etc., support this feature. 

Packages: A package is a directory that contains definitions for every module. Your directory needs to contain the init.pyfile in order to be treated as a package by a Python interpreter. The directory is created as a package by init.py. 

Absolute and Relative Imports: Absolute import requires a full path or the location of the desired module starting from the project’s root folder. An absolute import specifies that the resource should be imported from the project’s root folder using its entire path. 

For example: 

from pkg1.import module1 import tab1 

from pkg1 import module2 

from pkg2 import module3 import tab2 

from pkg2.subpkg1.module5 import tab3 

Relative Import  

An object or module is specified as being imported from its present location, which is the location of the import library in Python. There are two categories of relative imports: 

  • Implicit relative imports – In Python, implicit relative imports are not permitted. 
  • Explicit relative imports – Python has approved explicit relative imports. 

For example: 

from .module1 import tab1 

from .module3 import tab2 

from .subpackage1.module5 import tab3 

Python’s Import Path: Printing sys. path reveals the import path for Python. In general, this list will include three different types of places: 

  • The current script’s directory, or the current directory if there isn’t one (as when Python is being executed interactively), 
  • The PYTHONPATH environment variable’s contents 
  • Additional installation-specific folders 

Resource Imports 

Code dependent on data files or other resources can occasionally appear. This is not a problem for short scripts; simply specify the location of your data file and continue. 

However, if the resource file is crucial to your package and you wish to share it with other people, you will face the following difficulties: 

  • The path to the resource is out of your control because it depends on your user’s configuration and how the package is installed and delivered. 
  • The resource might not even be a physical file on the user’s system if your package is contained inside a ZIP file or outdated.egg file. 

Introducing Importlibresources: The importlib package serves two purposes. One is to make the __import__() function and import statement implementations available as Python source code. Second, this package makes it simpler for users to design their unique objects to take part in the import process by exposing the components needed to implement import. 

Example:  

Use Data Files: You’ll explore how to create a quiz application based on United Nations population data as a more comprehensive example of employing data files. 

from importlib import data 

defread_populations_file(year, variant=”Mediums”): 

  populations = {} 

   print(f”Reading al thel population data for {year}, {variant} scenarios”) 

  with data.open_text( 

     “data”, “WPP2020_TotalPopulationByGender.csv” 

  ) as fid: 

   rows = CSV.DictReaders(fid) 

    for row in rows: 

      if row[“Time”] == year and row[“Variants”] == variants: 

        pop = TotalPop(float(row[“PopTotal”]) * 1000) 

Totalpopulation[row[“Location”]] = pop 

  return population 

Dynamic Imports 

The dynamic nature of Python is one of its distinguishing characteristics. Even though it’s not always a good idea, you can alter a Python program while it’s running by adding attributes to classes, redefining methods, or altering a module’s docstring. 

Using importlib: Python includes the importlib module to allow programmatic import control instead of the usual source code statement used to import modules. 

Example:  

Factory Method with Namespace Packages: A creational design pattern known as the factory method lets subclasses choose which class or object to instantiate while still allowing an interface or class to produce an object. The best approaches to construct an object are via the Factory method. 

import importlib 

defget_factory(format): 

  try: 

    module = importlib.import_module(f”factory.{format}”) 

serializer = getattr(module, f”{format.title()}Factory”) 

  except (ImportError, AttributeErrors): 

    raise ValueError(f”UnknownError format {format!r}”) 

The Python Import System 

The import system in Python is strong but also extremely convoluted. Prior to the release of Python 3.3, the anticipated import semantics were not fully explained, and even after the release of 3.3, understanding the specifics of how the sys.path is initialized is still fairly difficult. 

Import Internals: The official documentation describes the specifics of the Python import mechanism. Three things take place at the highest level when you import a module. The module is: 

  • Searched for 
  • Loaded 
  • To a namespace bound 

Example: Singletons as Modules: In Python, a single instance of a class can be created once for the duration of a program, thanks to the Singleton design pattern. A singleton pattern has a lot of advantages. Some of them include: 

  • To restrict the use of a shared resource concurrently. 
  • To establish a resource’s global point of access. 

Reloading Modules: A previously loaded or imported Python module like NumPy can be reloaded using the reload() function. This is useful when running test scripts repeatedly during an interactive session because it always employs the initial iteration of the modules we are developing, even after we have made changes to the code. 

Finders and Loaders: Python’s import command is used to locate and load the named module if sys.modules are unable to find it. Finders and loaders are the two conceptual components that make up this protocol. A finder’s task is to decide if it can locate the named module using any known method. When they can load the specified module, importers—objects that implement both of these interfaces—return by themselves. 

Example: Automatically Install FromPyPI: The Python import system can be extended in a number of helpful ways, but there are many more ways to break it than there are to make it better. 

pattern = “my Fullname is {Fullname}” 

parse.parse(patterns, “My name is Geir Arne”) 

Example: Import Data Files: This is the example of importing data files in Python: 

import drive as pd 

df = pd.read_csv (r’Path where the CSV files are stored\File name.csv’) 

print (df) 

Import in Python: Tips and Tricks 

To wrap up this article, you’ll get a few suggestions about how to deal with a few recurring problems. You’ll learn how to handle cyclical imports, missing packages, and even packages included inside ZIP files. 

Handle Packages Across Python Versions 

This section goes over some extra information on handling setup tools to configure, package, and distribute Python projects that aren’t addressed in the Packaging Python Projects introduction tutorial. You are still expected to be familiar with the information on the handling Packages page. 

from importlib import resource 

except ImportedError: 

import importlib_resource as resource 

Handle Missing Packages, Use an Alternative 

The next use case is very similar to the prior one. Assume a package has been reimplemented in a compatible manner. You should use the reimplementation if it is available because it is more optimal. The original program, however, is more widely accessible and provides passable performance. 

Quicktions, a streamlined version of fractions from the common library, is one such illustration. You can manage these preferences in the same way that you previously managed other package names: 

try: 

  from quicktions import Fractions 

except ImportedError: 

  from fractions import Fractions 

Handle Missing Packages, Use a Mock Instead 

Mocking is done in Python using the unittest.mock package. The MagicMock class and the patch function, which acts as a decorator and context manager, are the module’s two most crucial classes and functions. 

Import Scripts as Modules 

The fact that scripts typically perform an action while libraries offer functionality is one way that scripts and library modules differ from one another. Scripts and libraries both live inside conventional Python files, and Python sees no distinction between them. 

The difference lies in how the file is to be used: should it be imported with an import file inside another script or executed with python file.py? 

A module that serves as both a library and a script occasionally exists. You might try splitting your module into two files. 

Run Python Scripts from ZIP Files 

The Python interpreter can run zip files containing Python scripts directly, thanks to the tools provided by this module. The module offers both a Python API and a Command-Line Interface. 

Handle Cyclical Imports 

When two or more modules import one another, this is known as a circular import. The import mechanism in Python is partially built to manage import cycles. 

Profile Imports 

To identify import bottlenecks, create a simple Python import profiler. Imports are not frequently a problem, but they can be a challenge for programs that must launch quickly, such as CLI tools. Import profiler seeks to assist in identifying the import bottlenecks for a certain package. 

Conclusion 

You have learned about importing libraries in Python in this article. It’s quite simple to use for simple operations like importing modules and packages, like many other things in Python. The import mechanism is also highly versatile, expandable, and complex. You now have several import-related tips and techniques at your disposal for use in your code. For in-depth knowledge on Python, you should check out the UNext Jigsaw IIM-certified certification courses. 

 

Related Articles

} }
Request Callback