Should I write import statements in each file in python - python

I have three files: module_one.py module_two.py module_three.py which each has a class for itself in it:
# module_one.py
from module_two import ModuleTwo
from module_three import ModuleThree
class ModuleOne:
...
# module_two.py
from module_one import ModuleOne
from module_three import ModuleThree
class ModuleTwo:
...
# module_three.py
from module_one import ModuleOne
from module_two import ModuleTwo
class ModuleThree:
...
I have a file main.py which looks like this:
# main.py
from module_one import ModuleOne
from module_two import ModuleTwo
from module_three import ModuleThree
... # and uses them
Which is the entry point of the application and uses those module classes.
In each of those module files (module_*.py) as you see I have to import other modules to use them. Isn't there any better way to manage this? can I write a statement in main.py and after that those module files that get loaded in the memory can see each other and call on themselves without having to import each other in their own files first?

Related

ImportError: attempted relative import with no known parent package/ Python/ unittesting

List item
I am trying to import the class Store from file grocery.py but am unable to do so using init.py.
Below is my file structure-
Main_folder
Grocery
__init__.py
grocery.py(which contains class Store())
tests
__init__.py
test_grocery.py
Codes are below:
test_grocery.py
'''
import unittest
from ..Grocery.grocery import Store
class TestCases(unittest.TestCase):
def test_cases_getSubTotal(self):
store1 = Store()
store1.activate()
self.assertTrue(store1.is_active())
def test_cases_getDiscount(self):
store2 = Store()
store2.add_points(25)
self.assertEqual(store2.get_points(), 25)
if __name__ == '__main__':
unittest.main()
'''
terminal
'''
from ..Grocery.grocery import Store
ImportError: attempted relative import with no known parent package
'''
Your import has to only contain the class_name.py and then import the function or class. Imports are also case sensitive.
from Grocery import Store
You cannot import from the parent directory unless you modify sys.path

how to make relative import between 2 classes in same directory in python?

I have the following files in my directory:
`directory/
__init__.py
GUI.py
Data.py`
file GUI.py looks like this:
import os
import tkinter as Tk
from .Data import data
class GUI(object):
def __init__(self):
do things ...
file Data.py looks like this:
import os
class data(object):
do things ...
class data2(object):
do other things ...
I tried to run the GUI.py but get the following error for the from .Data import data
ERROR: SystemError: Parent module '' not loaded, cannot perform relative import
I use the import as it written in the relative import documentation. Why doesnt it work?
The following should work:
from Data import data

python: how to import a module

I'm a newbie in using Python.
What I need is simple: import a module dynamically.
Here is my little test:
#module
class Test:
def func(self, id, name):
print("Your ID: " + str(id) + ". Your name: " + name)
return
I put this class in a file named my_module.py and the path of the file is: c:\doc\my_module.py.
Now I create a new python project to import the file above.
Here is what I do:
import sys
module = sys.path.append(r'c:\doc\my_module.py')
myClass = module.__class__
print(myClass)
However, I got this result:
<class 'NoneType'>
Why can't I get Test?
Is it because the way to import a module is wrong or because I need to do some config to import a module?
You're doing it wrong. Here's how you should import your module with sys.path.append:
import sys # import sys
sys.path.append(r'c:\doc\') # add your module path to ``sys.path``
import my_module # now import your module using filename without .py extension
myClass = my_module.Test # this is how you use the ``Test`` class form your module
try this:
import sys
sys.path.append(r'c:\doc\') # make sure python find your module
import my_module # import your module
t = my_module.Test() # Initialize the Test class
t.func(1, 'test') # call the method
The way to import a module is through the import command. You can specify the path with sys as a directory. You also need to instantiate the class within the module (through the my_module.Test()). See the following:
import sys
sys.path.append(r'c:\doc\\')
import my_module
myObj = my_module.Test()
myClass = myObj.__class__
print(myClass)

Importing function from nested_directory/filename.py

I have following directory structure:
V1.0/
module/
answer_type/
__init__.py
worker.py
src/
__init__.py
ans_type/
__init__.py
sent_process.py
module_two/
module_three/
I have put __init__.py file in directory so that it can be imported. But still it does not allow to import the class from inner most file.
sent_process.py looks like
from light_lizer.result_initiator import ResultInitiator
import re
import sys
import gearman
import sys,json
class QueryPylinkAnsTypeDetector(GearManOverride):
def __init__(self, config):
super(QueryAnsTypeDetector, self).__init__(config)
self.init_log()
def init_log(self):
print "__init_log"
self.abs_path = os.path.abspath(__file__).replace(os.getcwd(),'').replace('/','-').replace('.py','').replace('.','_')
self.log_set_obj = LogSetting(type(self).__name__)
self.logger = self.log_set_obj.logger
def preProcessLink(self, link):
new_link = link[-2:]
return new_link
def processSentenceSingle(self, read_str):
post_script_link_list = []
linkage[0] = 'xyz'
post_script_link_list = self.preProcessLink(linkage[0])
return result
in worker.py I am trying to import function from sent_process.py
from src.ans_type.sent_process import QueryPylinkAnsTypeDetector as PylinkProcess
gives error: from src.answer_type.pylink_process import QueryPylinkAnsTypeDetector
ImportError: No module named src.ans_type.sent_process
Can someone please suggest what is wrong here?
Update:
Being in V1.0 directory, I am executing worker in this way:
python - m module/answer_type/worker

How to import variables defined in __init__.py?

I'm a little confused about how importing works. Assume:
package/
__init__.py
file1.py
In __init__.py:
from file1 import AClass
__version__ = '1.0'
In file1.py:
Class AClass(object):
def bar():
# I want to use __version__here, but don't want to pass
# it through the constructor. Is there any way?
pass
If I use from . import __version__ in file1.py it just says ImportError: cannot import name __version__.
You've got a circular dependency because both files try to import each other. Move __version__ to a separate module, say package/version.py, then import that in both others with
from .version import __version__
Try:
__version__ = '1.0'
from file1 import AClass
You need to assign the constants before you import the module so that it'll be in place when you try to import it.
EDIT: larsmans suggestion to avoid the circular dependency is a good idea.

Categories