crazydiv
crazydiv

Reputation: 842

Modularizing python code

I have around 2000 lines of code in a python script. I decided to cleanup the code and moved all the helpers in a helpers.py file and all the configs and imports in a config.py file Here my main file:

from config import *
from helpers import *
from modules import * 

And in my config file I've writted

import threading as th

And then in modules I am extending a thread class

class A(th.Thread):
...

I get an error that th is not defined.And when I import config in my modules class, it works fine. I don't have a clear picture on how imports work here. Also, is there any best practice to do it?

Upvotes: 1

Views: 1250

Answers (2)

Lie Ryan
Lie Ryan

Reputation: 64923

Python's from module import * isn't the same as require/include that you may see in other languages like PHP.

The star import works by executing/loading the module first, then merging the module's namespace to the current namespace. This means that module have to import its own dependencies itself. You can do that by adding from config import * in module, or better to do import threading as th in module as well.

Upvotes: 4

Veedrac
Veedrac

Reputation: 60207

Read import threading as th as th = __import__("threading"): it's an assignment first and foremost. Thus, you have to do the import in every file where you're using the variable.

PS: import * is best avoided.

Upvotes: 4

Related Questions