1

I'm a Java guy, and I always used to think about the import keyword as a command to importing external classes and methods (packages)...

In Python I saw that it is slightly different... here you can use import to add some code and functions from another file and even add some classes from another file...

So when you want to execute a function from a file.py you have to write:

import file
file.function()

And if you want to execute a method from a class in class.py you have to write:

import class
object = class()
object.method()

My little java mind can't understand why do they have the same syntax... does it mean that when you create an external file with some function you are unknowingly creating an object?

Or the python team has just used the same keyword and syntax for two different scopes?

Sorry if I wrote some incorrect concepts, I just tried to explain it easily

iSaidAloha
  • 21
  • 4

1 Answers1

0

When you import a module, it is added to the programs symbol table. A symbol table is a dict that stores necessary information about the current program/file and is used by the compiler. To illustrate this, we can create two separate files:

# main.py

import file
# file.py

x = 25

def func():
    pass

In main.py, when you say import file, a separate namespace is created and added to the local symbol table of main.py. This is the reason for the syntax where you must say file.x or file.func(). To view the local symbol table, write print(locals()) in main.py. As stated before, the symbol table is a dictionary. That means you can access elements inside of the symbol table by key. For example, in main.py:

print(locals()['file'])

# <module 'file' from 'path/to/file.py'>

If you don't want the entirety of file.py to be imported, you can use the from/import syntax. In main.py, replace import file with:

from file import x

As you can probably guess, x is added to the local symbol table of main.py. Now, you don't have to use file.x to access it - in fact, that will throw an error because the compiler doesn't know what file is.

print(x)

# 25

Modules and classes are completely different. A great explanation of the difference between classes and modules is posted here.

gmdev
  • 2,725
  • 2
  • 13
  • 28