Skip to content
Advertisement

Imported And Standalone Functions [closed]

There were logical errors and typo on my code, have been edited and published here

First file: foo.py

import bar
def myname_foo():
    if __name__=='foo':
        print("foo: I have been imported")
    if __name__=='__main__':
        print("foo: I am on my own, i.e., standalone")

if __name__=='__main__':
    myname_foo()
    bar.myname_bar()

Second file: bar.py

import foo
def myname_bar():
    if __name__=='bar':
        print('bar: I have been imported')
    if __name__=='__main__':
        print('bar: I am on my own, i.e., standalone')

if __name__=='__main__':
    myname_bar()
    foo.myname_foo()

The outputs are:

$ python foo.py
foo: I am on my own, i.e., standalone
bar: I have been imported
$ python bar.py
bar: I am on my own, i.e., standalone
foo: I have been imported

Advertisement

Answer

you should check better your code

import foo
def myname_bar():
    if __name__=='foo':
                  ^^^ bar  


if __name__=='__main__':
    myname_bar()
    bar.myname_foo()
    ^^^ foo

after that

$ python  foo.py
foo: I am on my own, i.e., standalone
bar: I have been imported

$ python  bar.py
bar: I am on my own, i.e., standalone
foo: I have been imported
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement