Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

Keyword from

In an import, bind a selected member to a local name, optionally through an alias.

Version: Python 3.14; repository image, production runtime not attested

Syntax

from package import member as local

In an import, bind a selected member to a local name, optionally through an alias.

Rebinding the module attribute later does not update the imported binding. In raise ... from, an exception becomes the explicit cause. In yield from, a generator delegates iteration and can receive a subgenerator’s final return value. One leading dot selects the current package and each extra dot moves up one level.

Star imports are restricted to module level and use the names in __all__, or names without a leading underscore if it is absent.

Examples

import types
import sys
module = types.ModuleType("local_prices_example")
module.rate = 2
sys.modules[module.__name__] = module
from local_prices_example import rate as saved
module.rate = 3
print(saved, module.rate)
def inner():
    yield saved
    return module.rate
def outer():
    final = yield from inner()
    yield final
print(list(outer()))
try:
    try:
        raise ValueError("input")
    except ValueError as cause:
        raise RuntimeError("context") from cause
except RuntimeError as error:
    print(type(error.__cause__).__name__)
module._hidden = 4
scope = {}
exec("from local_prices_example import *", scope)
assert scope["rate"] == 3 and "_hidden" not in scope
module.__all__ = ["_hidden"]
scope = {}
exec("from local_prices_example import *", scope)
assert scope["_hidden"] == 4 and "rate" not in scope
try:
    compile("def bad():\n    from math import *", "<module>", "exec")
except SyntaxError:
    pass
else:
    raise AssertionError("star outside module")
scope = {"__package__": "xml.etree"}
exec("from . import ElementTree\nfrom .. import etree", scope)
assert scope["ElementTree"].__name__ == "xml.etree.ElementTree" and scope["etree"].__name__ == "xml.etree"

Result

2 3
[2, 3]
ValueError

Star imports are restricted to module level and use the names in `__all__`, or names without a leading underscore if it is absent.

Sources