How does Imported modules work in python?

Viewed 59

I am importing a module named as dependency.py inside another module app.py. I am curious to know that when I compile app.py into app.pyc, does app.pyc include the byte code of relevant code segment from dependency.py ? Or does app.pyc include an instruction to open and read from dependency.py?

app.py is as follows:

 from dependency import myfunc
 print("inside app.py")
 myfunc()

dependency.py is as follows:

def myfunc():
      print("inside dependency")

Now there are two possible scenarios:

scenario 1. app.pyc looks like

byte code corresponding to <print("inside app.py")>
byte code corresponding to <print("inside dependency")>

scenario 2. app.pyc looks like

byte code corresponding to <print("inside dependency")>
byte code corresponding to the instruction <open dependency.py and then read what myfunc means>

I tried to run app.pyc after deleting dependency.py and it throws error saying - ModuleNotFoundError: No module named 'dependency'. So it seems that scenario 2 is true. But I don't have a cs background and new in programming world, So I'm asking you if I am right or something different is happening?

1 Answers

Unless you have the following at the end of your .py files (replacing method_name with the method you're creating):

if __name__ == '__main__':
    method_name()

what will likely happen is when you import the module, the imported module will run first followed by the code under your import call. In your example, you'd see myfunc run then lines 2 and 3 of app.py. It would print:

inside my dependency
inside app
inside dependency

The code at the top essentially checks a special variable of the code you're running to see if the interpreter should run the code. It's to avoid running the code on import unless you explicitly call the code within your app.

When you delete dependency, anything trying to use that now deleted module will throw an error because it's getting confused because it can't find it. So if you un-delete it, that ModuleNotFoundError will go away.

Related