I made a sample file that uses a class called Names. It has its initialization function and a few methods. When I create an instance of the class it retrieves the instance's first name and last name. The other methods greet the instance and say a departure message. My question is: how do I import this file into the Python shell without having to run the module itself?
The name of my file is classNames.py and the location is C:\Users\Darian\Desktop\Python_Programs\Experimenting
Here is what my code looks like:
class Names(object):
#first function called when creating an instance of the class
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
#class method that greets the instance of the class.
def intro(self):
print "Hello {} {}!".format(self.first_name, self.last_name)
def departure(self):
print "Goodbye {} {}!".format(self.first_name, self.last_name)
But I get the error:
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
import classNames.py
ImportError: No module named classNames.py
I am not clear about what you expect and what you see instead, but the handling of your module works exactly like the math and any other modules:
You just import them. If this happens for the first time, the file is taken and executed. Everything what is left in its namespace after running it is available to you from outside.
If your code only contains just def, class statements and assignments, wou won't notice that anything happens, because, well, nothing "really" happens at this time. But you have the classes, functions and other names available for use.
However, if you have print statements at top level, you'll see that it is indeed executed.
If you have this file anywhere in your Python path (be it explicitly or because it is in the current working directory), you can use it like
import classNames
and use its contents such as
n = classNames.Names("John", "Doe")
or you do
from classNames import Names
n = Names("John", "Doe")
Don't do import classNames.py, as this would try to import module py.py from the package classNames/.
Related
I have been learning working with classes in python after learning OOPs in c++.
I am working on a project, where I have a class defined in one file, and an important function to be used in the class in the seperate file.
I have to call the class in the first file, but I am getting the ImportError.
Great, if you could help.
try1.py
from try2 import prnt
class a:
def __init__(self):
print("started")
def func1(self):
print("func1")
prnt()
try2.py
from try1 import a
b = a()
b.func1()
def prnt():
b.func()
As for eg, in the above example, when I am running try1.py, I am getting an ImportError: cannot import name 'prnt'.
You absolutely need to redesign your project. Even if you did manage to get away with the cyclic imports (ie by moving the import to inside the function - but don't do it) you will still get a NameError: name 'b' is not defined since b is not define in prnt.
Unless prnt can't be defined in class a (why?), consider defining prnt in a third, "utils" file and import it in both try1.py and try2.py and pass an object to it so it can access all of its attributes.
Just run your code, read the error, and deduct something from it.
When you run it, here is the error message :
Traceback (most recent call last):
File "C:\Users\Kilian\Desktop\Code\Garbage\tmp.py", line 7, in <module>
from temp2 import prnt
File "C:\Users\Kilian\Desktop\Code\Garbage\temp2.py", line 1, in <module>
from tmp import a
File "C:\Users\Kilian\Desktop\Code\Garbage\tmp.py", line 7, in <module>
from temp2 import prnt
ImportError: cannot import name prnt
Your script is trying to import something it already has tried to import earlier on. Python is probably deducing that it can't import it. :)
I have two modules misc.py and main.py and would like to define all classes present in misc.py in main.py.
Below is the code
#misc.py
class dummy:
def __init__(self):
pass
def dummyPrint(self):
print "Welcome to python"
#main.py
import misc
dummyObj = dummy()
dummyObj.dummyPrint()
Is this the right way to go ? I do not see any output i.e., Welcome to python
$python misc_main.py misc.py
EDIT: I added the statement from misc import dummy and i am getting the following error
$python misc_main.py main.py
Traceback (most recent call last):
File "misc_main.py", line 5, in <module>
dummyObj = dummmy()
NameError: name 'dummmy' is not defined
When you do the following command, you are calling misc_main.py from the interpreter with misc.py as an argument.
python misc_main.py misc.py
Since misc_main is not reading command line arguments, this is equivalent to
python misc_main.py
I am surprised that you do not get errors, in either case. You need to import the actual class if you want to get output.
from misc import dummy
dummyObj = dummy()
dummyObj.dummyPrint()
Note, I am assuming your main file is actually in called misc_main.py rather than main.py as you have stated in your question. Otherwise you are not invoking the correct file.
I have the module Test.py with class test inside the module. Here is the code:
class test:
SIZE = 100;
tot = 0;
def __init__(self, int1, int2):
tot = int1 + int2;
def getTot(self):
return tot;
def printIntegers(self):
for i in range(0, 10):
print(i);
Now, at the interpreter I try:
>>> import Test
>>> t = test(1, 2);
I get the following error:
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
t = test(1, 2);
NameError: name 'test' is not defined
Where did I go wrong?
You have to access the class like so:
Test.test
If you want to access the class like you tried to before, you have two options:
from Test import *
This imports everything from the module. However, it isn't recommended as there is a possibility that something from the module can overwrite a builtin without realising it.
You can also do:
from Test import test
This is much safer, because you know which names you are overwriting, assuming you are actually overwriting anything.
Your question has already been answered by #larsmans and #Votatility, but I'm chiming in because nobody mentioned that you're violating Python standards with your naming convention.
Modules should be all lower case, delimited by underscores (optional), while classes should be camel-cased. So, what you should have is:
test.py:
class Test(object):
pass
other.py
from test import Test
# or
import test
inst = test.Test()
When you do import Test, you can access the class as Test.test. If you want to access it as test, do from Test import test.
I've got a class that I'm trying to write called dbObject and I'm trying to import it from a script in a different folder. My structure is as follows:
/var/www/html/py/testobj.py
/var/www/html/py/obj/dbObject.py
/var/www/html/py/obj/__init__.py
Now, __init__.py is an empty file. Here are the contents of dbObject.py:
class dbObject:
def __init__():
print "Constructor?"
def test():
print "Testing"
And here's the contents of testobj.py:
#!/usr/bin/python
import sys
sys.path.append("/var/www/html/py")
import obj.dbObject
db = dbObject()
When I run this, I get:
Traceback (most recent call last):
File "testobj.py", line 7, in <module>
db = dbObject()
NameError: name 'dbObject' is not defined
I'm new to Python, so I'm very confused as to what I'm doing wrong. Could someone please point me in the right direction?
EDIT: Thanks to Martijn Pieters' answer I modified my testobj.py as follows:
#!/usr/bin/python
import sys
sys.path.append("/var/www/html/py")
sys.path.append("/var/www/html/py/dev")
from obj.dbObject import dbObject
db = dbObject()
However, now when I run it I get this error:
Traceback (most recent call last):
File "testobj.py", line 7, in <module>
db = dbObject()
TypeError: __init__() takes no arguments (1 given)
Is this referring to my init.py or the constructor within dbObject?
EDIT(2): Solved that one myself, the constructor must be able to take at least one parameter - a reference to itself. Simple fix. Looks like this problem is solved!
EDIT (Final): This is nice - I can cut out the import sys and sys.path.append lines and it still works in this instance. Lovely.
You need to import the class from the module:
from obj.dbObject import dbObject
This adds the class dbObject directly to your local namespace.
Your statement import obj.dbObject adds the name obj to the local namespace, so you could also do this instead:
db = obj.dbObject.dbObject()
because obj.dbObject is the dbObject.py module in your obj package directory.
I'm using Python for a weeks now and i'm confronted to an issue with dynamic import.
I have a file Test.py that in which a class is defined. I would like to use this class after the dynamic import of Test.py from another file.
My final goal is more complex but I simplified it but i still get the same problem.
File : Test.py
class Test :
def __init__ ( self ) :
print ( "instance" )
File : Main.py
def allImports ( ) :
__import__ ( "Test" )
What i get :
>>> import Main
>>> Main.allImports()
>>> myInstance = Test ()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'Test' is not defined
I cannot specify in the fromlist which element from Test.py i have to import because i'm not supposed to know them.
What should i do ?
For a solution closer to your intent:
import importlib
def allImports(globals):
mod = importlib.import_module('Test', globals['__name__'])
try:
keys = mod.__all__
except AttributeError:
keys = dir(mod)
for key in keys:
if not key.startswith('_'):
globals[key] = getattr(mod, key)
# …
allImports(globals())
Test # should work, you can also look into dir(Test) to find the class.
If your module doesn't have an __all__ the code above /will/ clobber your namespace something fierce. Either make sure you define __all__, or modify allImports() to only import the things you want. (E.g. only classes, or only classes defined in the module. This part really depends on your use case.)
When using __import__() to load a module, you have to look it up in sys.modules:
>>> import sys
>>> import Main
>>> Main.allImports()
>>> myInstance = sys.modules['Test'].Test()
instance
>>>
More information in the documentation and here, here, and here.
this code makes __import__ ( "Test" ) a local variable, so you can't access it outside the function.
def allImports ( ) :
__import__ ( "Test" )
try:
def allImports ( ) :
test= __import__ ( "Test" )
return test #return the module
>>> import Main
>>> x=Main.allImports() #store the returned module in x
>>> myInstance = x.Test ()
instance
>>>myInstance
<Test.Test instance at 0x011D7F80>
__import__ doesn't modify magically neither global nor local namespaces.
Modules and classes are first class citizens in Python i.e., you can use them as any other object in Python (bind to a name, pass as a parameter to a function, return as a value from a function).
def allImports():
return __import__("Test")
Test_module = allImports()
Test = Test_module.Test # class
test_instance = Test()
If the above code is inside a function then to put Test into global namespace: globals()['Test'] = Test. Note most probably you don't need it and there are better ways to do whatever you want without modifying global namespace inside a function.
Usage of __import__() is discouraged use importlib.import_module() instead.
If the name of the module and the class are known you could just write at the module level:
from Test import Test