NameError: global name is not defined - python

I'm using Python 2.6.1 on Mac OS X.
I have two simple Python files (below), but when I run
python update_url.py
I get on the terminal:
Traceback (most recent call last):
File "update_urls.py", line 7, in <module>
main()
File "update_urls.py", line 4, in main
db = SqliteDBzz()
NameError: global name 'SqliteDBzz' is not defined
I tried renaming the files and classes differently, which is why there's x and z on the ends. ;)
File sqlitedbx.py
class SqliteDBzz:
connection = ''
curser = ''
def connect(self):
print "foo"
def find_or_create(self, table, column, value):
print "baar"
File update_url.py
import sqlitedbx
def main():
db = SqliteDBzz()
db.connect
if __name__ == "__main__":
main()

You need to do:
import sqlitedbx
def main():
db = sqlitedbx.SqliteDBzz()
db.connect()
if __name__ == "__main__":
main()

try
from sqlitedbx import SqliteDBzz

Importing the namespace is somewhat cleaner. Imagine you have two different modules you import, both of them with the same method/class. Some bad stuff might happen. I'd dare say it is usually good practice to use:
import module
over
from module import function/class

That's How Python works.
Try this :
from sqlitedbx import SqliteDBzz
Such that you can directly use the name without the enclosing module.Or just import the module and prepend 'sqlitedbx.' to your function,class etc

Related

Can't import functions/modules

I'm simply trying to import a function from another script. But despite import running successfully, the functions never enter my local environment.
The paths and files look like this:
project/__main__.py
project/script_a.py
from setup import script_b
x = ABC() # NameError: name 'ABC' is not defined
print(x)
project/setup/__init__.py
project/setup/script_b.py
def ABC():
return "ABC"
I've done this before and the documentation (officials and on here) is quite straightforward but I cannot grasp what I am failing to understand. Is the function running but never entering my environment?
I also tried using...
if __name__ == '__main__':
def ABC():
return "ABC"
...as script_b.
Import the functions inside the module:
from setup.script_b import ABC
Or call the function on the modules name like said in the comments
x = script_b.ABC()

Python import from script outside package

Python unable to import package, but works correctly from within the package. A fully functional example below. In the virtual env I am using 3.6 All responses greatly appreciated!
parsers/
__init__.py
element.py
parser1.py
parser2.py
parserresolver.py
outsidepkg.py
init.py is empty
element.py:
def router():
pass
parser1.py:
from element import *
def parse(data):
return data
parser2.py:
from element import *
def parse(data):
return data
parserresolver.py:
import sys
from parser1 import *
from parser2 import *
def resolve(data):
parseddata = None
parsers = ['parser1', 'parser2']
funcname = 'parse'
for parser in parsers:
module = sys.modules[parser]
if hasattr(module, funcname):
func = getattr(module, funcname)
parseddata = func(data)
print(parseddata)
return parseddata
if __name__ == "__main__":
resolve('something')
outsidepkg.py:
import parsers.parserresolver
def getapi(data):
parsers.parserresolver.resolve(data)
if __name__ == "__main__":
print(getapi('in parse api main'))
So when I call parserresolver.py directly it works great, no import errors and prints out "something" as expected.
But when I call outsidepkg.py I am getting this error:
Traceback (most recent call last):
File "C:\code\TestImport\TestImport\outsidepkg.py", line 1, in <module>
import parsers.parserresolver
File "C:\code\TestImport\TestImport\parsers\parserresolver.py", line 2, in <module>
from parser1 import *
ModuleNotFoundError: No module named 'parser1'
Press any key to continue . . .
You need to change the imports of:
from file import whatever
To:
from .file import whatever
Since your code to run it is outside the folder, use a . to get the directory, since the file isn't outside the package.

Using python function from other python file and subsequent class?

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. :)

Python Creating and Importing Modules

I wrote functions that are applyRules(ch), processString(Oldstr) and named it lsystems.py
And I put
import lsystems
def main():
inst = applyRules("F")
print(inst)
main()
and saved it as mainfunctioni
However, when I try to run mainfunctioni, it says 'applyRules' is not defined.
Doesn't it work because I put import lsystems?
What should I do to work my mainfunctioni through lsystems?
You have to call it with module.function() format. So in this case, it should be called like as follows:
inst = lsystems.applyRules("F")
You have to access all the methods from your module with the same format. For processString(Oldstr), it should be similar.
test_string = lsystems.processString("Somestring")
When you import a module using import <module> syntax, you need to access the module's contents through its namespace, like so:
import lsystems
def main():
inst = lsystems.applyRules("F")
print(inst)
main()
Alternatively, you can directly import the function from the module:
from lsystems import applyRules
def main():
inst = applyRules("F")
print(inst)
main()

Writing and importing custom modules/classes

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.

Categories

Resources