Python import package by string

Import Python Module by String Name

In Python, when building a framework or code generation tool, you might need to programmatically build a string representing the name of a module you want to import. How would you import a module if you have it’s name as a string? Here’s how to do it with importlib! Note that this feature was introduced in Python 3.1 but there is a 2.7 version of importlib though less featured.

Learn more about how Python searches for imports, how the `PYTHONPATH` environment variable is used, and how to use `sys.path` in my Python import, sys.path, and PYTHONPATH Tutorial.

Learn more about Python virtual environments which allow you to create isolated Python environments with different import paths with my Python Virtual Environments Tutorial.

Use importlib to programmatically import modules

The importlib provides a simple import_module function that accepts a string name with dot separators. It works just like a normal import except it uses a string to store the name. On import, the file is executed and the module object is returned. If you only need the code run on import it is not necessary to store the returned module.

import importlib

# Contrived example of generating a module named as a string
full_module_name = "mypackage." + "mymodule"

# The file gets executed upon import, as expected.
mymodule = importlib.import_module(full_module_name)

# Then you can use the module like normal
mymodule.func1()
mymodule.func2()

Conclusion

You should now know how to dynamically import modules using a module name stored in a string.

Источник

How to import modules from string in Python?

How to import modules from string in Python?

Dynamic module importing made easy with Python's importlib

In Python, you can use the import statement to import a module or package into your code. However, sometimes you may want to dynamically import a module or package from a string, rather than hard coding the module or package name. In this article, we'll explore how to import modules from string in Python using the importlib module.

The importlib module provides a number of functions for interacting with the import system, including the import_module function, which can be used to import a module from a string. To use the import_module function, you need to pass it the name of the module as a string, and it will return the module object.

For example, to import the math module from a string, you can use the following code:

import importlib module_name = 'math' module = importlib.import_module(module_name) 

Once you have the module object, you can use it like any other module, accessing its attributes and functions using the dot notation. For example, to use the pi constant from the math module, you can use the following code:

import importlib module_name = 'math' module = importlib.import_module(module_name) print(module.pi) # 3.141592653589793 

You can also use the import_module function to import submodules or subpackages from a string. To do this, you simply need to include the submodule or subpackage name in the string, separated by a dot. For example, to import the urllib.parse module from a string, you can use the following code:

import importlib module_name = 'urllib.parse' module = importlib.import_module(module_name) 

In addition to the import_module function, the importlib module also provides the import_from_string function, which allows you to import a module or object from a string containing the fully qualified name of the module or object. For example, to import the Decimal class from the decimal module from a string, you can use the following code:

import importlib module_name = 'decimal.Decimal' module = importlib.import_from_string(module_name) decimal = module('3.14') print(decimal) # 3.14 

In conclusion, the importlib module provides a number of functions for importing modules and objects from string in Python. By using these functions, you can dynamically import modules or objects

Any thoughts? Write it down in the comments.

For more such crispy blogs daily, follow Dev.Junction, subscribe to our newsletter and get notified.

Did you find this article valuable?

Support Dev.Junction by becoming a sponsor. Any amount is appreciated!

Источник

How to Import Python Module from String Name

In this Python tutorial, we will explore how to import a Python Module using a string representation of its name. We will achieve this task using the Python importlib module, which provides us with the required functionality.

It is important to note that this library is only available on Python 2.7, and Python 3.1 and above.

Import Python Module using importlib

Normally, when we want to import modules/libraries in Python, we follow the below format.

However, we may wish to import libraries during run-time, or based on user input. This may lead us to trying the following approach(es).

import "matplotlib" # Wrong str = "matplotlib" import str # Wrong

Both of the above approaches are wrong, and will not work as intended. This is where the Python importlib library comes in.

We will be using the importlib library’s import_module() function. This function takes as parameter, a string that represents the library you wish to import.

Let’s take a look at how to import a module using this function.

import importlib lib = importlib.import_module("random") for i in range(5): print(lib.randint(1, 10))

Once you have called import_module() function, it will return a library object. Every time you want to use a function from the imported library, you must do it through the library object.

In the above example, we imported the random library, used to generate random numbers. It has a variety of different functions, one of which is randint() . Normally we might do random.randint() to call this, but when using importlib, we need to do lib.randint() . ( lib is an arbitrary name)

More about importlib

Some special cases can arise, such as when you need to import a sub-module. The below code shows how you would go about doing so.

import importlib lib = importlib.import_module("matplotlib.pyplot") lib.plot([1, 2, 3, 4], [1, 4, 9, 16]) lib.show()

Normally, this would have been the following statement.

For more information about importlib, please refer to the dedicated section for the Python importlib module.

This marks the end of the “Import Python Module from String” Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the tutorial content can be asked in the comments section.

Источник

Читайте также:  Sys python удалить файл
Оцените статью