I am trying to import a module via another module. My code is as the following:
main.py
import init
myInsert = Insert()
init.py
from insert import Insert
insert.py
class Insert:
def __init__(self):
print('insert is innitiated')<br>
It means that i am trying to have an init file to load all modules I need for later times.
For example I am trying to load insert module by init module and then use it in main.py.
Unfortunately an error occures when I run main.py which is as followes:
NameError: name 'Insert' is not defined
Could you please tell me what am i doing wrong and how to make it work?
Here:
import init
myInsert = Insert()
The name Insert is indeed not defined. Where does it come from? Not from init, because names that come from that module would be referenced as init.name, so it must be global. But it's not defined anywhere else (there's no assignment like Init = <thing>, no star imports like from init import *), so here's an error.
You're looking for:
myInsert = init.Insert()
Related
I have my own repository created in BitBucket.
In that repository, I have a file named core.py and an __init__.py file
I tried to import the core module, and I fixed all the requirements that were needed.
Now when I am finally able to import the module using ipython, which is only one big class, with the call:
obj = MyClass()
I get an error:
name 'MyClass()' is not defined
even though it seems the module was imported.
Let me know if more information is Needed.
As you stated in your comment, you are importing core.py:
from mintigocloudstorage import core
That means, you also have to tell your script where to find your class:
obj = core.MyClass()
If the import was sucessfull as you say, Python should now be able to locate your classes definition.
Alternatively you can also import your class:
from mintigocloudstorage.core import MyClass
obj = MyClass()
I have a custom package called 'package' and a custom module in that package called 'module' which has a function returning 'test' when called. When I import my package if I do:
from package import module
Everything works fine but if I do:
from package import *
Or
import package
Then when trying to use the 'module' module it comes up with an error name 'module' is not defined. Why is it not importing the module when I use import * or when I import the package?
The code in the module I am trying to call is this:
def printTest():
return("Test")
The code in the file calling the module is this:
import package
print(module.printTest())
This is a surprisingly common issue and this question was still without an proper answer, so here we go.
Let's suppose we have a module only with functions inside, say:
file app/foo.py:
def a():
print('Hello from foo.a')
def b():
print('Hello from foo.b')
I would genuinely expect this to work (but it DOESN'T):
file app/bar.py:
import app.foo
# These will not work!
foo.a()
foo.b()
It turns out that you have to import each element explicitly or give app.foo a name:
Import everything (usually considered a bad practice):
from app.foo import *
# Both will work fine
a()
b()
Import only what you want:
from app.foo import b
# This will work
b()
# But this will not
a()
Give app.foo a (nice) name:
import app.foo as baz
# Both will work as expected
baz.a()
baz.b()
Even if the examples above use only functions, it works exactly the same for everything declared at the top most scope of the module, like classes or variables.
Hope it helps!
If you just want to execute the script outside the original file, you can try:
exec(open('filename').read())
it may be more suitable than using import?
I was facing the same issue, turns out that the file that I wanted to import has the name in lowercase like this global.py once I changed it to Global.py and added
import Global as glb
in main.py (the file where I wanted to import) everything worked as expected.
I've written a basic program with a couple of classes, and I've had two issues I would like help with. All of the files are in the same directory, and my classes are in files with the same name as the class.
First, my class files can only import with the format
from module import class
I can't use the format
import module
Second, I've only been able to use my classes if I do the import inside of main. When I import at the beginning of the file, I get an unboundlocalerror when creating an object. I've had these issues (especially the 1st one) on more than one program. Any ideas?
Thanks!
You cannot, as you found out, use
import class
You either have to use
from module import class
And you'd call the class simply as
class # note you don't have the module namespace
Or if you'd like to keep the namespace (which I'd recommend)
import module
Then you can say
module.class
module.otherclass
...etc
As you found, you cannot just type:
import class
as that would lead python to believe that you wanted to import a module named class, when what you want is the class inside the module. That is why
from module import class
does work, as it shows python where 'class' is.
I am working my way through the excellent 'Python The Hard Way' and copied the following code into a file called mystuff.py:
class MyStuff(object):
def __init__(self):
self.tangerine = "And now a thousand years between"
def apple(self):
print "I AM CLASSY APPLES!"
In terminal:
import mystuff
thing = MyStuff()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'MyStuff' is not defined
This has been happening repeatedly with other simple classes today. Can someone tell me what I am doing wrong?
You probably want thing = mystuff.MyStuff() (assuming mystuff is the name of the file where the class MyStuff resides).
The issue here is with how python handles namespaces. You bring something into the current namespace by importing it, but there's a lot of flexibility in how you merge the namespaces from one file into another. For example,
import mystuff
brings everything from the mystuff (module/file level) namespace into your current namespace, but to access it, you need mystuff.function_or_class_or_data. If you don't want to type mystuff all the time, you can change the name you use to reference it in the current module (file):
import mystuff as ms
now, you can acess MyStuff by:
thing = ms.MyStuff()
And (almost) finally, there's the from mystuff import MyStuff. In this form, you bring MyStuff directly into your namespace, but nothing else from mystuff comes into your namespace.
Last, (and this one isn't recommended) from mystuff import *. This works the same as the previous one, but it also grabs everything else in the mystuff file and imports that too.
You are importing the module in to your local namespace, but not the class. If you want to use the class with your current import, you need:
thing = mystuff.MyStuff()
If you want to use the declaration you have, you need:
from mystuff import MyStuff
Ok,I guess u got what u need.But here is what's going on with it
import mystuff
#with this type of import all the names in the `mystuff` module's namespace are not copied into current modules namespace.
So you need to use mystuff.MyStuff()
use from mystuff import * to copy names in the mystuff module's namespace to current module's namespace.Now you can directly use thing=MyStuff()
Is it only possible if I rename the file? Or is there a __module__ variable to the file to define what's its name?
If you really want to import the file 'oldname.py' with the statement 'import newname', there is a trick that makes it possible: Import the module somewhere with the old name, then inject it into sys.modules with the new name. Subsequent import statements will also find it under the new name. Code sample:
# this is in file 'oldname.py'
...module code...
Usage:
# inject the 'oldname' module with a new name
import oldname
import sys
sys.modules['newname'] = oldname
Now you can everywhere your module with import newname.
You can change the name used for a module when importing by using as:
import foo as bar
print bar.baz
Yes, you should rename the file. Best would be after you have done that to remove the oldname.pyc and oldname.pyo compiled files (if present) from your system, otherwise the module will be importable under the old name too.
When you do import module_name the Python interpreter looks for a file module_name.extension in PYTHONPATH. So there's no chaging that name without changing name of the file. But of course you can do:
import module_name as new_module_name
or even
import module_name.submodule.subsubmodule as short_name
Useful eg. for writing DB code.
import sqlite3 as sql
sql.whatever..
And then to switch eg. sqlite3 to pysqlite you just change the import line
Every class has an __module__ property, although I believe changing this will not change the namespace of the Class.
If it is possible, it would probably involve using setattr to insert the methods or class into the desired module, although you run the risk of making your code very confusing to your future peers.
Your best bet is to rename the file.
Where would you like to have this __module__ variable, so your original script knows what to import? Modules are recognized by file names and looked in paths defined in sys.path variable.
So, you have to rename the file, then remove the oldname.pyc, just to make sure everything works right.
I had an issue like this with bsddb. I was forced to install the bsddb3 module but hundreds of scripts imported bsddb. Instead of changing the import in all of them, I extracted the bsddb3 egg, and created a soft link in the site-packages directory so that both "bsddb" and "bsddb3" were one in the same to python.
You can set the module via module attribute like below.
func.__module__ = module
You can even create a decorator to change the module names for specific functions in a file for example:
def set_module(module):
"""Decorator for overriding __module__ on a function or class.
Example usage::
#set_module('numpy')
def example():
pass
assert example.__module__ == 'numpy'
"""
def decorator(func):
if module is not None:
func.__module__ = module
return func
return
and then use
#set_module('my_module')
def some_func(...):
Pay attention since this decorator is for changing individual
module names for functions.
This example is taken from numpy source code: https://github.com/numpy/numpy/blob/0721406ede8b983b8689d8b70556499fc2aea28a/numpy/core/numeric.py#L289