Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing python modules for use in only one file

More specifically let's say I have a number of .py files, with main.py importing stuff like os, pygame, math and all my other .py files, mymodule01.py etc.

My problem is that whenever main.py calls on one of my .py files and that file contains something like an os.listdir() I keep getting an error saying stuff like 'os is not defined'.

Should I just import all the required modules in each .py file I write, or is there a better way, like a centralized import that every file can recognize? With pygame especially this would be very confusing since I'd have to init pygame in each file just to use it's functions, not to mention if I want to blit something on the screen.

The python modules and packages documentation didn't help much, that or I'm really slow, also considering that after following the doc I keep getting a not found error after adding e.g. import mymodule01.py in the init.py file in the containing folder.

like image 846
user1079328 Avatar asked Dec 03 '11 19:12

user1079328


People also ask

How can I import modules if file is not in same directory?

We can use sys. path to add the path of the new different folder (the folder from where we want to import the modules) to the system path so that Python can also look for the module in that directory if it doesn't find the module in its current directory.

Do I need to import in every Python file?

Python does not actually import a module that it has already imported (unless you force it to do so with the reload function), so you can safely put a import some_module statement into every module of your program that needs access to the names defined in some_module .

How do I import a specific module in Python?

Importing Modules To make use of the functions in a module, you'll need to import the module with an import statement. An import statement is made up of the import keyword along with the name of the module. In a Python file, this will be declared at the top of the code, under any shebang lines or general comments.

Do Python modules need to be in the same folder?

Answer. No, files can be imported from different directories.


1 Answers

Should I just import all the required modules in each .py file I write

Yes.

With pygame especially this would be very confusing since I'd have to init pygame in each file just to use it's functions

No, only init it once. There's only one copy of the module.

like image 188
kindall Avatar answered Oct 20 '22 19:10

kindall