Python : Cannot find any functions within my own module? - python

I have created my own module with filename mymodule.py. The file contains:
def testmod():
print "test module success"
I have placed this file within /Library/Python/2.7/site-packages/mymodule/mymodule.py
I have also added a __init__.py file, these have compiled to generate
__init__.pyc and mymodule.pyc
Then in the python console I import it
import mymodule
which works fine
when I try to use mymodule.testmod() I get the following error:
AttributeError: 'module' object has no attribute 'testmod'
So yeah it seems like it has no functions?

You have a package mymodule, containing a module mymodule. The function is part of the module, not the package.
Import the module:
import mymodule.mymodule
and reference the function on that:
mymodule.mymodule.testmod()
You can use from ... import and import ... as to influence what gets imported exactly:
from mymodule import mymodule
mymodule.testmod()
or
from mymodule import mymodule as nestedmodule
nestedmodule.testmod
or
from mymodule.mymodule import testmod
testmod()
etc.

Related

Python: A problem with the package import from ... import * using __all__ and __init__

I have the following Python package with 2 moludes:
-pack1
|-__init__
|-mod1.py
|-mod2.py
-import_test.py
with the code:
# in mod1.py
a = 1
and
# in mod2.py
from mod1 import a
b = 2
and the __init__ code:
# in __init__.py
__all__ = ['mod1', 'mod2']
Next, I am trying to import the package:
# in import_test.py
from pack1 import *
But I get an error:
ModuleNotFoundError: No module named 'mod1'
If I remove the dependency "from mod1 import a" in mod2.py, the import goes correctly. But that dependency makes the import incorrect with that exception "ModuleNotFoundError".
???
The issue here is that from mod2 perspective the first level in which it will search for a module is in the path from which you are importing it (here I am assuming that pack1 is not in your PYTHONPATH and that you are importing it from the same directory where pack1 is contained).
This means that if pack1 is in the directory /dir/to/pack1 and you do:
from mod1 import a
Python will look for mod1 in the same directory as pack1, i.e., /dir/to/pack1.
To solve your issue it is enough to do either:
from pack1.mod1 import a
or in Python 3.5+
from .mod1 import a
As a side note, unless this is a must for you, I do not recommend designing your package to be used as from pack import *, even if __all__ exists to give you better control of your public API.

Python Paths - ImportError: cannot import name 'dataset_builder'

I am getting an error ImportError: cannot import name 'dataset_builder'. The import command is following:
from object_detection.builders import dataset_builder
The file tree looks following:
-ObjectDetection
-train.py
-models
-research
-object_detection
-builders
- __init__.py
-dataset_builder.py
I am running the train.py from the root directory (os.getcwd() returns following path C:\Users\horakm\PyCharmProjects\ObjectDetection) and I added in the train.py following code to add paths:
sys.path.append(r'C:\Users\horakm\PyCharmProjects\ObjectDetection\models')
sys.path.append(r'C:\Users\horakm\PyCharmProjects\ObjectDetection\models\research')
sys.path.append(r'C:\Users\horakm\PyCharmProjects\ObjectDetection\models\research\slim')
When I print all paths using sys.path i get this:
['C:\\Users\\horakm\\PyCharmProjects\\ObjectDetection',
'C:\\Users\\horakm\\PyCharmProjects\\ObjectDetection',
'C:\\Users\\horakm\\AppData\\Local\\Continuum\\miniconda3\\envs\\tf1_env\\python36.zip',
'C:\\Users\\horakm\\AppData\\Local\\Continuum\\miniconda3\\envs\\tf1_env\\DLLs',
'C:\\Users\\horakm\\AppData\\Local\\Continuum\\miniconda3\\envs\\tf1_env\\lib',
'C:\\Users\\horakm\\AppData\\Local\\Continuum\\miniconda3\\envs\\tf1_env',
'C:\\Users\\horakm\\AppData\\Roaming\\Python\\Python36\\site-packages',
'C:\\Users\\horakm\\AppData\\Roaming\\Python\\Python36\\site-packages\\win32',
'C:\\Users\\horakm\\AppData\\Roaming\\Python\\Python36\\site-packages\\win32\\lib',
'C:\\Users\\horakm\\AppData\\Roaming\\Python\\Python36\\site-packages\\Pythonwin',
'C:\\Users\\horakm\\AppData\\Local\\Continuum\\miniconda3\\envs\\tf1_env\\lib\\site-packages',
'C:\\Users\\horakm\\AppData\\Local\\Continuum\\miniconda3\\envs\\tf1_env\\lib\\site-
packages\\object_detection-0.1-py3.6.egg',
'C:\\Users\\horakm\\AppData\\Local\\Continuum\\miniconda3\\envs\\tf1_env\\lib\\site-packages\\win32',
'C:\\Users\\horakm\\AppData\\Local\\Continuum\\miniconda3\\envs\\tf1_env\\lib\\site-
packages\\win32\\lib',
'C:\\Users\\horakm\\AppData\\Local\\Continuum\\miniconda3\\envs\\tf1_env\\lib\\site-packages\\Pythonwin',
'C:\\Users\\horakm\\PyCharmProjects\\ObjectDetection\\models',
'C:\\Users\\horakm\\PyCharmProjects\\ObjectDetection\\models\\research',
'C:\\Users\\horakm\\PyCharmProjects\\ObjectDetection\\models\\research\\slim']
How is it possible that the import statement doesn't work?
Which object are you actually trying to import?
All that are defined in dataset_builder? In that case it should be from object_detection.builders.dataset_builder import *.
Or is the object also called dataset_builder? In that case it is from object_detection.builders.dataset_builder import dataset_builder.

Python ImportLib 'No Module Named'

I'm trying to use a variable as a module to import from in Python.
Using ImportLib I have been successfully able to find the test...
sys.path.insert(0, sys.path[0] + '\\tests')
tool_name = selected_tool.split(".")[0]
selected_module = importlib.import_module("script1")
print(selected_module)
... and by printing the select_module I can see that it succesfully finds the script:
<module 'script1' from 'C:\\Users\\.....">
However, when I try to use this variable in the code to import a module from it:
from selected_module import run
run(1337)
The program quits with the following error:
ImportError: No module named 'selected_module'
I have tried to add a init.py file to the main directory and the /test directory where the scripts are, but to no avail. I'm sure it's just something stupidly small I'm missing - does anyone know?
Import statements are not sensitive to variables! Their content are treated as literals
An example:
urllib = "foo"
from urllib import parse # loads "urllib.parse", not "foo.parse"
print(parse)
Note that from my_module import my_func will simply bind my_module.my_func to the local name my_func. If you have already imported the module via importlib.import_module, you can just do this yourself:
# ... your code here
run = selected_module.run # bind module function to local name

Python Module issues

Im pretty new to python, and have been having a rough time learning it. I have a main file
import Tests
from Tests import CashAMDSale
CashAMDSale.AMDSale()
and CashAMDSale
import pyodbc
import DataFunctions
import automa
from DataFunctions import *
from automa.api import *
def AMDSale():
AMDInstance = DataFunctions.GetValidAMD()
And here is GetValidAMD
import pyodbc
def ValidAMD(GetValidAMD):
(short method talking to a database)
My error comes up on the line that has AMDInstance = DataFunctions.GetValidAMD()
I get the error AttributeError: 'module' object has no attribute 'GetValidAMD'
I have looked and looked for an answer, and nothing has worked. Any ideas? Thanks!
DataFunctions is a folder, which means it is a package and must contain an __init__.py file for python to recognise it as such.
when you import * from a package, you do not automatically import all it's modules. This is documented in the docs
so for your code to work, you either need to explicitly import the modules you need:
import DataFunctions.GetValidAMD
or you need to add the following to the __init__.py of DataFunctions:
__all__ = ["GetValidAMD"]
then you can import * from the package and everything listen in __all__ will be imported
When you create the file foo.py, you create a python module. When you do import foo, Python evaluates that file and places any variables, functions and classes it defines into a module object, which it assigns to the name foo.
# foo.py
x = 1
def foo():
print 'foo'
 
>>> import foo
>>> type(foo)
<type 'module'>
>>> foo.x
1
>>> foo.foo()
foo
When you create the directory bar with an __init__.py file, you create a python package. When you do import bar, Python evaluates the __init__.py file and places any variables, functions and classes it defines into a module object, which it assigns to the name bar.
# bar/__init__.py
y = 2
def bar():
print 'bar'
 
>>> import bar
>>> type(bar)
<type 'module'>
>>> bar.y
2
>>> bar.bar()
bar
When you create python modules inside a python package (that is, files ending with .py inside directory containing __init__.py), you must import these modules via this package:
>>> # place foo.py in bar/
>>> import foo
Traceback (most recent call last):
...
ImportError: No module named foo
>>> import bar.foo
>>> bar.foo.x
1
>>> bar.foo.foo()
foo
Now, assuming your project structure is:
main.py
DataFunctions/
__init__.py
CashAMDSale.py
def AMDSale(): ...
GetValidAMD.py
def ValidAMD(GetValidAMD): ...
your main script can import DataFunctions.CashAMDSale and use DataFunctions.CashAMDSale.AMDSale(), and import DataFunctions.GetValidAMD and use DataFunctions.GetValidAMD.ValidAMD().
Check out this.
It's the same problem. You are importing DataFunctions which is a module. I expct there to be a class called DataFunctions in that module which needs to be imported with
from DataFunctions import DataFunctions
...
AMDInstance = DataFunctions.GetValidAMD()

Import a module from a package

I'm trying to import a simple package, but it doesn't work.
I have a "package" directory that contains two files:
foo.py (with a function called fct)
__init__.py (with nothing in it)
Here is the content of tests.py:
import package.foo
foo.fct(7)
But it doesn't work.
If I change the import line to from package.foo import fct, I can execute the function.
You need import package.foo as foo or one of the alternatives below ...
import package.foo
package.foo.fct(7)
or:
import package.foo as foo
foo.fct(7)
or possibly:
from package import foo
foo.fct(7)

Categories