How does the plug-in class access the variable and modules of the main program? For example, the main file:

# <main.py> PYTHON_VERSION = 3 if PYTHON_VERSION == 3: from urllib.parse import urlencode, quote # python 3 else: from urllib import urlencode, quote # python 2.7 import mymodule 

The class in the mymodule module does not see the global variable PYTHON_VERSION:

 # <mymodule.py> class works: global PYTHON_VERSION def get_html(self): print (PYTHON_VERSION) # ошибка: name 'PYTHON_VERSION' is not defined 

neither quote from urllib :

 # <mymodule.py> class works: PYTHON_VERSION = 3 # ... def get_html(self): if self.PYTHON_VERSION == 3: url = self.URLhtml + quote(self.title) # python 3 else: url = self.URLhtml + self.title.encode('utf-8') # python 2.7 # ошибка: name 'quote' is not defined 

In one file, without putting it into the module and classes, just functions, everything worked.

  • one
    Uh, global is sort of like to make a local (default) variable in a global function. If you need a common variable for several modules, it is better to put it in a separate module. And about urllib: it will need to be imported at the beginning of mymodule.py - hunter

1 answer 1

No If you need constants common to several modules, put these constants in a separate module and import it in the other modules.

In your case, you can do this:

Create a constans.py file

 from sys import version_info PYTHON_VERSION = version_info.major if PYTHON_VERSION == 3: from urllib.parse import urlencode, quote # python 3 else: from urllib import urlencode, quote # python 2.7 

Then import it into the remaining files:

mymodule.py

 from constans import PYTHON_VERSION, urlencode, quote class Works: def get_html(self): print(PYTHON_VERSION) # напечатает "3" 

main.py

 from constans import PYTHON_VERSION from mymodule import Works print( PYTHON_VERSION ) # напечатает 3 w = Works() w.get_html() # вызовет get_html которые напечатает 3