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()
Related
I have a project organized in directories as follows:
|main_dir/
| /__init__.py
| /core/
| /__init__.py
| /foo.py
| /test1.py
| /scr/
| /test2.py
In foo.py, I define a class as follows
class foo(object):
def __init__(self):
pass
This is what I have in core/test1.py
from foo import foo
f1=foo()
print(type(f1))
This is what I have in scr/test2.py:
import sys
sys.path.append('../')
from core.foo import foo
f2 = foo()
print(type(f2))
main_dir/__init__.py contains this:
__all__ = ["core"]
import sys, os
dir = os.path.dirname(__file__)
for subpackage in __all__:
sys.path.append(os.path.join(dir,subpackage))
and core/__init__.py contains:
__all__ = ["foo"]
import sys, os
dir = os.path.dirname(__file__)
for subpackage in __all__:
sys.path.append(os.path.join(dir,subpackage))
When I run test1.py, the result is class 'foo.foo'> while when I run test2.py, I get <class 'core.foo.foo'>. I understand that this is how Python behaves, but I am not sure how to get around it. I would like to get True when checking type(f1) == type(f2) as I need to access the object foo for different locations.
Add the first two lines from test2.py:
import sys
sys.path.append('../')
to the top of test1.py. Then change your imports of foo in test1.py and test2.py to use the fully-qualified name:
from main_dir.core.foo import foo
Afterward:
# core/test.py
<class 'main_dir.core.foo.foo'>
# scr/test2.py
<class 'main_dir.core.foo.foo'>
I think in file core/test1.py You can try to import foo like this
from .foo import foo
with the dot before the file name to ensure that is the file in the same directory gave it a try
or
You can import foo using as like it down
from .foo import foo as foo_one
from core.foo import foo as foo_core
I hope I understand what do you need and I hope it will help
I'm trying to do a dynamic import (using "__import__()") of a submodule in web2py and it doesn't seem to be finding the submodule.
Here's an example path:
web2py/app/modules/module.py <-- This works
web2py/app/modules/module_folder/submodule.py <-- This won't get spotted.
Right now as a workaround I'm using 'exec()' but I'd rather not do that.
Answers to questions:
"Do you have __init__.py in module_folder?"
Yep.
"What exactly is the line of code you write to import web2py/app/modules/module_folder/submodule.py?"
mapping_module = __import__('communication_templates.mappings.%s' % module_name)
"what is the error?"
<type 'exceptions.AttributeError'> 'module' object has no attribute 'mapping_dict'
Explanation: I'm trying to get a variable named 'mapping_dict' from the module once I've loaded it.
The problem here is that __import__ does not do the most intuitive thing (neither does import btw).
Here's what happens:
>>> import sys
>>> x = __import__('package1.package2.module')
>>> x
<module 'package1' from 'C:\\Temp\\package1\\__init__.py'>
Even though package1.package2.module was imported, the variable returned is actually package1.
So, to access something that is in package1.package2.module, one has to dig down again:
>>> x.package2.module.Class
<class 'package1.package2.module.Class'>
Is it then the same as importing just package1?
Not really:
>>> x = __import__('package1')
>>> x
<module 'package1' from 'C:\\Temp\\package1\\__init__.py'>
>>> x.package2.module.Class
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'package1' has no attribute 'package2'
Why?
Well, __import__ is the same as `import, that is, these are the same:
package1 = __import__('package1.package2.module')
# is the same as:
import package1.package2.module
And:
package1 = __import__('package1')
# is the same as:
import package1
In each of those cases, you get just one local variable package1.
In the case of importing package1.package2.module, package2 is also imported and stored in package2 attribute of package package1 etc.
Solution
To access package1.package2.module.Class, if package1.package2.module is in a string:
>>> s = 'package1.package2.module'
>>> module = __import__(s)
>>> for submodule_name in s.split('.')[1:]:
... module = getattr(module, submodule_name)
...
>>> module.Class
<class 'package1.package2.module.Class'>
File structure:
./__init__.py
a.py
/lib
__init__.py
Foo1.py # contains `class Foo1`
Foo2.py # contains `class Foo2`
# so on ...
Tested this in a.py and worked, doing this;
from lib.Foo1 import Foo1
from lib.Foo2 import Foo2
But, when I do from lib import * the __all__ = ["Foo1", "Foo2"] in __init__.py it doesn't work.
Error: <type 'exceptions.TypeError'>: 'module' object is not callable
What I'm missing?
Here is a.py;
#!/usr/bin/python
import cgi, cgitb
cgitb.enable()
from lib import *
print "Content-Type: text/html"
print ""
print "Test!"
foo1 = Foo1()
foo2 = Foo2()
Used these refs:
http://docs.python.org/2/tutorial/modules.html#importing-from-a-package
How to load all modules in a folder?
from lib import *
Will import everything in lib to the current module, so our globals() looks like:
{'Foo1':<module lib.Foo1>,
'Foo2':<module lib.Foo2>}
Whereas
from lib.Foo1 import *
from lib.Foo2 import *
Makes our globals() become
{'Foo1':<class lib.Foo1.Foo1>,
'Foo2':<class lib.Foo2.Foo2>}
So in the first case we're just importing modules, not the classes inside them which is what we want.
When importing * from a package (as in your case, using the __all__ in init.py) __all__ specifies all modules that shall be loaded and imported into the current namespace.
So, in your case, from lib import * will import the modules Foo1 and Foo2 and you need to access the classes like so:
foo1 = Foo1.Foo1()
foo2 = Foo2.Foo2()
Have a look at Importing * in Python for a quick clarification.
Add the following to your .../lib/__init__.py file:
from Foo1 import Foo1
from Foo2 import Foo1
__all__ = ['Foo1', 'Foo2']
Note that PEP-8 recommends that package and modules names be all lowercase to avoid confusion.
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.
I have a package named 'package'within that i have modules module1.py and module2.py i imported the package as
import package
from package import module1
In module1 i have a function named funcwhenever i import that function as
from module1 import func
and use it, the function as
module1.func(x)
it doesn't work
What is the problem and what should be done??
You can do either:
from module1 import func
func(x)
OR
module1.func(x)
Real world example which should demonstrate how things work:
>>> import os
>>> os.path.abspath("C:/Documents")
'C:\\Documents'
>>>
>>> from os import path
>>> path.abspath("C:/documents")
'C:\\documents'
>>>
>>> from path import abspath
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named path
>>>
>>> from os.path import abspath
>>> abspath("C:/documents")
'C:\\documents'
You can either import as:
from foo import bar
bar(baz)
or:
import foo
foo.bar(baz)
In certain cases, it may also be helpful to:
from foo import bar as qux
qux(baz
There is an extensive tutorial on handling imports available as well.
2 options:
from package.module1 import func
func(x)
2nd option:
from package import module1
module1.func(x)