Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NameError: global name is not defined

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() 
like image 509
Wizzard Avatar asked Oct 20 '10 11:10

Wizzard


People also ask

How do you fix NameError name is not defined?

The Python "NameError: name is not defined" occurs when we try to access a variable or function that is not defined or before it is defined. To solve the error, make sure you haven't misspelled the variable's name and access it after it has been declared.

How do you define a NameError in Python?

NameError is a kind of error in python that occurs when executing a function, variable, library or string without quotes that have been typed in the code without any previous Declaration. When the interpreter, upon execution, cannot identify the global or a local name, it throws a NameError.

Why am I getting name errors in Python?

In Python, the NameError occurs when you try to use a variable, function, or module that doesn't exist or wasn't used in a valid way. Some of the common mistakes that cause this error are: Using a variable or function name that is yet to be defined.

How do I fix name errors in Python?

You can fix this by doing global new at the start of the function in which you define it. This statement puts it in the global scope, meaning that it is defined at the module level. Therefore, you can access it anywhere in the program and you will not get that error.


2 Answers

You need to do:

import sqlitedbx  def main():     db = sqlitedbx.SqliteDBzz()     db.connect()  if __name__ == "__main__":     main() 
like image 100
SilentGhost Avatar answered Sep 22 '22 16:09

SilentGhost


try

from sqlitedbx import SqliteDBzz 
like image 24
joaquin Avatar answered Sep 20 '22 16:09

joaquin