Мои файлы пакета находятся в каталоге pkg:
Код: Выделить всё
pkg:
__init__.py, main.py, commands.py, queries.py
Код: Выделить всё
my_directory
Код: Выделить всё
main.py
Код: Выделить всё
import importlib.util
import sys
script_file = 'my_directory/run.py'
spec = importlib.util.spec_from_file_location('my_script', script_file)
mod = importlib.util.module_from_spec(spec)
sys.modules[script_file] = mod
spec.loader.exec_module(mod)
Код: Выделить всё
commands.py:
from queries import report, Format
def list_data(fmt: Format = Format.ASCII):
report(fmt)
Код: Выделить всё
queries.py:
from enum import auto, Enum
class Format(Enum):
ASCII = auto()
PYTHON = auto()
def report(fmt):
if fmt == Format.PYTHON:
print('Format is Python')
else:
print('Same values:', fmt == Format.PYTHON)
print('Same types:', type(fmt) == type(Format.PYTHON))
print(f'Formats: {fmt}, {Format.PYTHON}')
print('Module of Format:', Format.__module__)
print('Module of fmt:', fmt.__module__)
Код: Выделить всё
___init.py:
from .queries import Format
from .commands import list_data
Код: Выделить всё
from pkg import list_data, Format
list_data(Format.PYTHON)
Код: Выделить всё
Same values: False
Same types: False
Formats: Format.PYTHON, Format.PYTHON
Module of Format: queries
Module of fmt: pkg.queries
Как мне изменить свой код, чтобы получить ожидаемое поведение?
Прошу прощения за длинное описание, но мне не удалось воспроизвести проблему на меньшем примере.
Подробнее здесь: https://stackoverflow.com/questions/791 ... ed-modules