简体   繁体   中英

Python - UnboundLocalError: local variable referenced before assignment`

I'm writing a Python 3.6 script that works with Tkinter and an SQLite 3 database, but I get this error:

if "fImage" in globals() and not(fImage==None): UnboundLocalError: local variable 'fImage' referenced before assignment

The interested code is this:

from tkinter import *
from ttk import *
from tkinter import Toplevel, Tk
import sqlite3 as sql
def Salvataggio(mode,nome,cognome,sitoweb,email,idx):
    conn=sql.connect(os.path.join(path, fn_prof),isolation_level=None)
    c=conn.cursor()
    if mode=="add":
        if "fImage" in globals() and not(fImage==None):
            c.execute("INSERT INTO prof VALUES ('{}','{}','{}','{}','{}','{}')".format(len(prof.keys())+1,nome.get(),cognome.get(),fImage,sitoweb.get(),email.get()))
        else:                
            c.execute("INSERT INTO prof VALUES ('{}','{}','{}','{}','{}','{}')".format(len(prof.keys())+1,nome.get(),cognome.get(),"",sitoweb.get(),email.get()))
        del fImage
        wa.destroy()
    elif mode=="edit":
        if "fImage" in globals() and not(fImage==None):
            c.execute("""UPDATE prof
                      SET nome = '{}', cognome = '{}', imageURI='{}', web='{}', email='{}'
                      WHERE ID={}; """.format(nome.get(),cognome.get(),fImage,sitoweb.get(),email.get(),idx))
        else:                
            c.execute("""UPDATE prof
                      SET nome = '{}', cognome = '{}', web='{}', email='{}'
                      WHERE ID={}; """.format(nome.get(),cognome.get(),sitoweb.get(),email.get(),idx))
        del fImage
def selImmagine(bi):
    if not("fImage" in globals()):
        global fImage
    fImage=askopenfilename(filetypes=[(_("File Immagini"),"*.jpg *.jpeg *.png *.bmp *.gif *.psd *.tif *.tiff *.xbm *.xpm *.pgm *.ppm")])
    # other code...

Do you know how to solve this? The error results with the if and the elif in the salvataggio() function. Thanks

Remove:

del fImage

parts, it tries to remove fImage whether or not it exists.


See below Minimal, Complete, and Verifiable example :

def func():
    del variable_that_never_existed

func()

The proximal cause of your error is:

del fImage

which works like assignment, it causes fimage to be treated as local. Therefore, you are getting an unbound-local error, which makes sense, since you never assign to fImage in the first place in Salvataggio

Anyway, yours is a special case of the typical UnboundLocalError , because it didn't involve assignment to the variable to make it get marked as local. A common cause being a hidden assignment :

You get a plain name error if the variable is neither global nor local.

In [1]: def f():
   ...:     if x in {}:
   ...:         pass
   ...:

In [2]: f()
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-2-0ec059b9bfe1> in <module>()
----> 1 f()

<ipython-input-1-80c063ba8db6> in f()
      1 def f():
----> 2     if x in {}:
      3         pass
      4

NameError: name 'x' is not defined

However, the del marks the name as local:

In [3]: def f():
   ...:     if x in {}:
   ...:         pass
   ...:     del x
   ...:

In [4]: f()
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-4-0ec059b9bfe1> in <module>()
----> 1 f()

<ipython-input-3-5453b3a29937> in f()
      1 def f():
----> 2     if x in {}:
      3         pass
      4     del x
      5

UnboundLocalError: local variable 'x' referenced before assignment

This is why your check:

if "fImage" in globals() and not(fImage==None):

is the line where it fails. I do not understand why you always are checking whether fimage is in globals() . Note, 'fimage' in globals() can be true while fimage is a local name... hence the unbound local .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM