Importing function from nested_directory/filename.py - python

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

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

Python import statement doesn't work depending on position in __init__.py

Let's take a folder structure like this:
project_root
│ start.py
└───Application
└───ViewModels
│ __init__.py
│ MagnifierWindowViewModel.py
│ MainViewModel.py
│ MainWindowViewModel.py
│ PlotterWindowViewModel.py
These are the contents of the files:
start.py
from Application.ViewModels import MainViewModel
if __name__ == "__main__":
mainViewModel = MainViewModel()
Application\ViewModels\__init__.py
from Application.ViewModels.PlotterWindowViewModel import *
from Application.ViewModels.MagnifierWindowViewModel import *
from Application.ViewModels.MainViewModel import *
from Application.ViewModels.MainWindowViewModel import *
Application\ViewModels\MagnifierWindowViewModel.py
class MagnifierWindowViewModel(object):
def __init__(self):
pass
Application\ViewModels\MainViewModel.py
from Application.ViewModels import MagnifierWindowViewModel, MainWindowViewModel, PlotterWindowViewModel
class MainViewModel(object):
def __init__(self):
self.mainWindowVM = MainWindowViewModel()
self.magnifierWindowVM = MagnifierWindowViewModel()
self.plotterWindowVM = PlotterWindowViewModel()
Application\ViewModels\MainWindowViewModel.py
class MainWindowViewModel(object):
def __init__(self):
pass
Application\ViewModels\PlotterWindowViewModel.py
class PlotterWindowViewModel(object):
def __init__(self):
pass
With this structure, I get this error:
Traceback (most recent call last):
File "project_root/start.py", line 4, in <module>
mainViewModel = MainViewModel()
File "project_root/Application/ViewModels/MainViewModel.py", line 5, in __init__
self.mainWindowVM = MainWindowViewModel()
TypeError: 'module' object is not callable
But if I put the last line in Application\ViewModels\__init__.py first, the application runs just fine. Why is that?
The reason I have this Application\ViewModels\__init__.py is so that I can write
from Application.ViewModels import MagnifierWindowViewModel
instead of
from Application.ViewModels.MagnifierWindowViewModel import MagnifierWindowViewModel
You've stuck every class in its own module named the exact same thing as the class. That's a really bad idea for the reasons you're seeing here: it is way too easy to get the class and the module mixed up.
When your MainViewModel.py performs its imports:
from Application.ViewModels import MagnifierWindowViewModel, MainWindowViewModel, PlotterWindowViewModel
what gets imported depends on how much of Application\ViewModels\__init__.py has executed. If this line has not executed:
from Application.ViewModels.MainWindowViewModel import *
then the import in MainViewModel.py imports the MainWindowViewModel module. If the import * has executed, then it shadows the MainWindowViewModel module with the MainWindowViewModel class defined inside the module, so the import in MainViewModel.py imports the MainWindowViewModel class.

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)

A dynamic load __import__ reports no module error

Here is my directory structure:
In file keyword.py I import lottery.lottery at the first line like this:
from lottery.lotterya import Lottery
In file rule.py I import lottery.keyword dynamically like this:
__import('lottery.keyword') but it reports an error "No module named lotterya".
I don't know what to do. Can anyone help?
I dynamically import a module
Here is one solution for your question. It uses importlib to do dynamic import.
In ruly.py
import importlib
if __name__ == '__main__':
mKey = importlib.import_module('lottery.keyword')
MyKeyword = getattr(mKey,'MyKeyword')
k = MyKeyword()
k.mPrint()
In keyword.py
from lottery.lotterya import Lotterya
class MyKeyword():
def __init__(self):
pass
def mPrint(self):
print 'Hello, keyword'
l = Lotterya()
l.lPrint()
In lotterya.py
class Lotterya:
def __init__(self):
pass
def lPrint(self):
print 'Hello, Lotterya'

Categories