Passing variables in python when used from import *

How can I make this baz print when I run b.py?

a.py

    def foo():
        global bar
        print bar

b.py

    from a import *
    bar = "baz"
    foo()
+3
source share
4 answers

In this simple example, the real answer in most cases is to use function arguments (as already mentioned). But if it made sense to check Python's review rules, I think I can clarify ...

C/++, , Python. #include. C/++ #include / ( ). , , , #included. #includes, .:-P

Python , . , . . , , . "" . . , a.py b "bar".

, . , b: a.bar = bar ( ).

a.py,

def foo():
    print bar

b.py :

import a
a.bar = "baz"
a.foo()

a.py , b.py a.set_module_state( "baz" ).

+6

. a b, b .

from a import * b.py foo b , foo a . . b .

:

import a
bar = "baz"
a.foo(bar)

, a.bar, . foo(), b.

+2

python, ...

a.py
 def foo():
    print bar

b.py
 from a import *
 a.bar = "baz"
 foo()

from <module> import *. , . - , . , :

a.py
 def foo(bar):
    print bar

b.py
 import a
 bar = "baz"
 a.foo(bar)

, !

+1

, Python, , , "" ( ), globals.py:

a.py

    import globals
    def foo():
        #global bar
        print globals.bar

b.py

    import globals
    from a import *
    globals.bar = "baz"
    foo()

globals.py

    #This module contains global variables
    bar = ""

, , , - , , .

0

Source: https://habr.com/ru/post/1743540/


All Articles