Import python modules for use in only one file

In particular, let's say I have several .py files with main.py importing things like os, pygame, math and all other .py files, mymodule01.py, etc.

My problem is that whenever main.py calls one of my .py files and this file contains something like os.listdir (), I keep getting an error message saying "os is undefined" .

Should I just import all the necessary modules into each .py file that I write, or is there a better way, for example, centralized import, which each file can recognize? With pygame, this would be very confusing especially since I would have to initialize pygame in each file, just to use its functions, not to mention if I want something on the screen.

The documentation on python modules and packages did not help much, it is either very slow, and also considering that after the document is executed, I continue to receive an error not found after adding, for example, import the mymodule01.py file in the init .py file in the folder in which .

+4
source share
2 answers

Should I just import all the necessary modules into each .py file, I write

Yes.

This would be very confusing with pygame, since I would have to initialize pygame in each file in order to use its functions

No, just run it once. There is only one copy of the module.

+4
source

I think you might get the impression that โ€œimportโ€ acts like โ€œincludeโ€ in other languages. This is not true.

Each module object is single. There is no performance degradation or danger of initializing module code more than once.

In addition, each file has its own region, so in your example, if you define foo = 1 in main.py, foo will not appear in mymodule01.py . You will need to import main; main.foo import main; main.foo see this (not what you need)

You grumble, but it's much better than include

+4
source

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


All Articles