невозможно назначить глобальную переменную в подмодуле Python - PullRequest
0 голосов
/ 08 мая 2019

Я запутался после 25 лет программирования на Python.Почему эта штуковина (сжатая до минимума) печатает «Нет»?Я ожидаю, что объект "thing.implementation1.Juggernaut в 0xblahblahblah".Что здесь происходит?

main.py

import thing
thing.run()

вещь / __ init __. Py

from .implementation1 import init
from .implementation1.main import *

вещь / реализация1 / __ init __. Py

foo = None
class Juggernaut:
    pass
def init():
    global foo
    foo = Juggernaut()

вещь / реализация1 / main.py

from . import init, foo
def run():
    init()
    print(repr(foo))

1 Ответ

0 голосов
/ 08 мая 2019

Я нашел практическое решение, но до сих пор не понимаю, почему оно работает. Перемещение функции init из thing/implementation1/__init__.py в thing/implementation1/main.py устраняет проблему.

вещь / __ __ INIT. Ру

from .implementation1.main import *

вещь / выполнение решений1 / __ __ INIT. Р

foo = None
class Juggernaut:
    pass

вещь / выполнения решений1 / main.py

from . import Juggernaut
def init():
    global foo
    foo = Juggernaut()
def run():
    init()
    print(repr(foo))
...