AttributeError: module "myModule" has no attribute "myFunc2" - python

I have a module "myModule" with the following functions as attributes: "myFunc1()", "myFunc2()".
myFunc1() gets imported correctly, myFunc2() does not.
"myModule.py"
def myFunc1():
#'function does something'
return 'something'
def myFunc2():
#'function does something'
return 'something'
I have another script in this format:
import myModule
x1 = myModule.myFunc1()
x2 = myModule.myFunc2()
x1 gets assigned a value, x2 does not. I get
AttributeError: module "myModule" has no attribute "myFunc2"
I am sure the module was imported correctly, as myFunc1() ran correctly.
There is no circular import.
My local module name is unique and so is the name of the attribute.

Related

Can anyone help me howto import a module class?

I have a module example.py with the follow class:
class add:
def __init__(self, x, y):
self.x= x
self.y= y
def adding_two_nbr(self):
return self.x*self.y
when I import the module as the following i got error:
import example
obj = example.add(1,2)
obj.adding_two_nbr()
error:
AttributeError: 'add' object has no attribute 'adding_two_nbr'
The code works for me smoothly. Change the second block of code as
import example
obj = example.add(1,2)
print(obj.adding_two_nbr())
Save this file as import_file.py in the same directory as example.py and run import_file.py.
I think add class is already defined in python module so you need to change to another name
AttributeError: 'add' object has no attribute 'adding_two_nbr'
adding_two_nbr not defined in python add module.

Custom import finder only work for namespace with a `__path__` attribute

I got a remote namespace agency remote_names. And I can access remote modules afterimport remote_namesthen byremote_names.module_name. This works fine until one uses the following statements:
import remote_names.name # ImportError: No module named name
from remote_names.name import sub_module # ImportError: No module named name
And I can fix this by defining a custom finder and add it to sys.meta_path.
class RemoteImporter(object):
def __init__(self, modules, namespace):
self.modules = modules
self.namespace = namespace
self.modules.__path__ = self.namespaces # Mark----------------1
def find_module(self, fullname, path=None):
if fullname.partition('.')[0] == self.namespace:
# If import module in namespace, use self as module loader.
return self
return None
def load_module(self, fullname):
name = fullname.partition('.')[2]
if len(name) == 0: # the namespace itself
return self.modules
else:
module = self.modules[name]
sys.modules[fullname] = module
return module
But if I didn't set the __path__ of this agency (as to make it a package). This finder is never get called when I execute import statement. The document doesn't show this:
Quote
If the module is not found in the cache, then sys.meta_path is
searched (the specification for sys.meta_path can be found in PEP
302). The object is a list of finder objects which are queried in
order as to whether they know how to load the module by calling their
find_module() method with the name of the module. If the module
happens to be contained within a package (as denoted by the existence
of a dot in the name), then a second argument to find_module() is
given as the value of the path attribute from the parent package
(everything up to the last dot in the name of the module being
imported). If a finder can find the module it returns a loader
(discussed later) or returns None.
So is there a reason why the finder never get called when the name gets no __path__ and what other finder python uses to find the name?

Python dynamic import and __all__

I am facing a behaviour that I don't understand even through I feel it is a very basic question...
Imagine you have a python package mypackage containing a module mymodule with 2 files __init__.py and my_object.py. Last file contains a class named MyObject.
I am trying to right an automatic import within the __init__.py that is an equivalent to :
__init__.py
__all__ = ['MyObject']
from my_object import MyObject
in order to be able to do:
from mypackge.mymodule import MyObject
I came up with a solution that fill all with all classes' names. It uses __import__ (also tried the importlib.import_module() method) but when I try to import MyObject from the mymodule, it keeps telling me:
ImportError: cannot import name MyObject
Here is the script I started with :
classes = []
for module in os.listdir(os.path.dirname(__file__)):
if module != '__init__.py' and module[-3:] == '.py':
module_name = module[:-3]
import_name = '%s.%s' % (__name__, module_name)
# Import module here! Looking for an equivalent to 'from module import MyObject'
# importlib.import_module(import_name) # Same behaviour
__import__(import_name, globals(), locals(), ['*'])
members = inspect.getmembers(sys.modules[import_name], lambda member: inspect.isclass(member) and member.__module__.startswith(__name__) )
names = [member[0] for member in members]
classes.extend(names)
__all__ = classes
Can someone help me on that point ?
Many thanks,
You just need to assign attributes on the module: globals().update(members).

Python Namespaces and Modules

If I import a python module using a syntax like this:
import my_module
I can later use a number of simplest command to get an idea of what the module is, where it is located and etc. For example:
print(my_module)
outputs: module 'my_module' from 'my_module.py'
dir(my_module)
outputs: ['MyClass', 'builtins', 'doc', 'file', 'name', 'package', 'math', 'os', 'sys']
I even can find out an absolute path of the module by using:
print os.path.abspath( my_module.__file__ )
outputs: /Users/julia/Documents/classes/my_module.py
But if instead of import 'my_module' I would be using:
from my_module import MyClass
all I can is to:
print MyClass
which outputs: my_module.MyClass
I do see MyClass came from my_module file. But unfortunately that is all I can get since none of the commands I used to use to get the info on module doesn't work. Here is use and their output:
print dir(my_module.MyClass) NameError: name 'my_module' is not defined
print dir(my_module) NameError: name 'my_module' is not defined
print my_module name 'my_module' is not defined
What command(-s) should I be using while tracking down the imported modules brought with
from my_module import MyClass
syntax?
The Problem is that
from my_module import MyClass
only imports MyClass but not the whole Module.
If you want to know the name of the Module MyClass was imported from, you can use:
print MyClass.__module__
If you want to use other Stuff from the same Module you could use:
my_module = __import__(MyClass.__module__)
print dir(my_module)
But it would be far more easy to just write:
import my_module
Thanks Mr.Crash!
Here is the summary:
If the module was imported with:
from my_module import MyClass
don't call the module by using its name directly.
Instead get to it via class imported from this module (using class's module attr) such as:
print dir(MyClass.__module__)
print os.path.abspath( MyClass.__module__ )

Dynamic Importing in Python (Dotted statments)

I'm having trouble with the following code:
def get_module(mod_path):
mod_list = mod_path.split('.')
mod = __import__(mod_list.pop(0))
while mod_list:
mod = getattr(mod, mod_list.pop(0))
return mod
When I do get_module('qmbpmn.common.db_parsers') I get the error message:
AttributeError: 'module' object has no attribute 'db_parsers'.
However: import qmbpmn.common.db_parsers works perfectly fine.
When using __import__ to import submodules, you must pass the parent package as the fromlist argument:
>>> __import__("os.path")
<module 'os' from '/usr/lib/python2.6/os.pyc'>
>>> __import__("os.path", fromlist=["os"])
<module 'posixpath' from '/usr/lib/python2.6/posixpath.pyc'>
__import__ works with the dotted module path, so this should work
def get_module(mod_path):
return __import__(mod_path)
or more simply
get_module = __import__
Perhaps I am misunderstanding the problem
importing a package does not automatically import all the submodules into it's namespace. For example
import qmbpmn
does not mean that
qmbpmn.common.db_parsers
will automatically resolve

Categories

Resources