from

In Python, the from keyword is primarily used to import specific objects from a module into your current namespace. This allows you to use the imported components directly without needing to prefix them with the module name.

The from keyword is also used in generator functions to delegate part of its operations to another iterable and in exception handling to indicate exception chaining.

Python from Keyword Examples

Here’s a quick example of how to use the from keyword to import objects in Python:

Python
>>> from math import pi, sqrt
>>> print(pi)
3.141592653589793

>>> print(sqrt(16))
4.0

In this example, we use the from keyword to import the pi constant and the sqrt function from the math module. This allows us to use pi and sqrt directly in our code without prefixing them with math.

When it comes to generator functions, you can use the from keyword as shown below:

Python
>>> def generator():
...     yield from [1, 2, 3]
...

>>> for value in generator():
...     print(value)
...
1
2
3

In this example, yield from [1, 2, 3] automatically handles iterating through the list and yields the elements one by one.

Python from Keyword Use Cases

  • Importing specific functions, classes, or variables from a module to reduce namespace clutter
  • Improving code readability by directly using components from a module
  • Avoiding potential naming conflicts by only importing what you need
  • Delegating part of a generator’s operations to another iterable
  • Indicating exception chaining in exception handling

Tutorial

Python import: Advanced Techniques and Tips

The Python import system is as powerful as it is useful. In this in-depth tutorial, you'll learn how to harness this power to improve the structure and maintainability of your code.

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Jan. 6, 2025 • Reviewed by Dan Bader