Python Forum
ReferenceError: weakly-referenced object no longer exists
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
ReferenceError: weakly-referenced object no longer exists
#11
If cur object was destroyed I would expect a different error, not something from deep in the bowels of MySQL. I suppose something inside of cur could have gone away. Similar to the way you need to keep a handle for an image that you want to use in Tk.
Reply
#12
search_entr is a tkinter entry
Reply
#13
also, why is cur garbage collected.
Reply
#14
How would we know. You only provide a tiny peek at your code and don't show where cur is created. I am betting the problem is with the text reference returned by Tk.Entry. Try setting your search string to some literal and see if the problem goes away. If it does you know the problem is Tk.Entry.
Reply
#15
The following code is search_book.py, which will be imported into main.py

Full Code:

from tkinter import *
from tkinter import messagebox
from tkinter import StringVar
import tkinter.ttk
import pyautogui as pg
import mysql.connector as mc

def search_book():
    global password, username
    usern = pg.prompt("Username", "Enter your username")
    passw = pg.password("Password", "Enter your password")
    try:
        conn = mc.connect(host="localhost", db="Library", user=usern, passwd=passw)
    except:
        messagebox.showerror("Incorrect Credentials", "Those credentials are incorrect")
        exit()

    global cur
    cur = conn.cursor()
    form = Tk()
    form.geometry("500x200")
    form.resizable(False, False)
    form.title("Search for a book")
    top_lbl = Label(form, text="Search For A Book", font="Courier 26").pack()
    
    OptionList = [
    "Pick A Search Type",
    "Title",
    "Author",
    "ISBN",
    ] 

    global variable
    variable = StringVar(form)
    variable.set(OptionList[0])

    search_dropd = OptionMenu(form, variable, *OptionList)
    search_dropd.pack()

    global search_entr
    search_entr = Entry(form, width=45)
    search_entr.pack()

    submit_btn = Button(text="SUBMIT", command=submit, width=34).pack()
        

def submit():
    search_words = search_entr.get()
    search_type = variable.get()
    if search_type == "Pick A Search Type":
        messagebox.showerror("Invalid Choice", "'Pick A Search Type' is not a valid search type.")
    else:
        global results
        if search_type == "ISBN":
            cur.execute("SELECT * FROM Books WHERE ISBN = %s", (search_words,))
            results = cur.fetchball()
        if search_type == 'Title':
            cur.execute("SELECT * FROM Books where ITLE = %s", (search_words,))
            results = cur.fetchball()
        if search_type == "Author":
            cur.execute("SELECT * FROM Books WHERE AUTHOR = %s", (search_words,))
            results = cur.fetchball()

        show_results(results)
    
def show_results(results_list):
    for i in range(len(results_list)):
        print(results_list[i])
Reply
#16
You don't show how you call your functions, but I assume you call search_book() in order to display the GUI.
You declare cur as global but actually it does not exists in the global scope. Once it complete the execution of the search_book, there are no references to cur and it is destroyed.

So, why do you create cur in search_book in the first place. Why not create it in submit() where it is actually needed and used.
Ideally you should refactor your spaghetti code and not use globals at all. As you see it's terrible to debug problem in such code.

The other "solution" is to initialize cur in the global namespace, e.g. cur = None at the top, after the imports.

As a side note - you use GUI, but print result in stdout??? Not to mention mixing pyautogui and tkinter???
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#17
I moved cur to submit(). Works now. Thanks
Reply
#18
if you look at the mysql.connector source code you will see it uses weakref
class CMySQLCursor(MySQLCursorAbstract):

    """Default cursor for interacting with MySQL using C Extension"""

    _raw = False
    _buffered = False
    _raw_as_string = False

    def __init__(self, connection):
        """Initialize"""
        MySQLCursorAbstract.__init__(self)

        self._insert_id = 0
        self._warning_count = 0
        self._warnings = None
        self._affected_rows = -1
        self._rowcount = -1
        self._nextrow = (None, None)
        self._executed = None
        self._executed_list = []
        self._stored_results = []

        if not isinstance(connection, MySQLConnectionAbstract):
            raise errors.InterfaceError(errno=2048)
        self._cnx = weakref.proxy(connection)
So, actually the weakly referenced object is connection and it is destroyed, which leads to error in execute(), line 232

        if not self._cnx:
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Beginner: Code not work when longer list raiviscoding 2 817 May-19-2023, 11:19 AM
Last Post: deanhystad
  local varible referenced before assignment SC4R 6 1,517 Jan-10-2023, 10:58 PM
Last Post: snippsat
  a longer docstring Skaperen 8 1,657 Aug-25-2022, 11:21 PM
Last Post: Skaperen
  UnboundLocalError: local variable 'wmi' referenced before assignment ilknurg 2 1,907 Feb-10-2022, 07:36 PM
Last Post: deanhystad
  Referenced before assignment finndude 3 3,264 Mar-02-2021, 08:11 PM
Last Post: finndude
  IDLE editing window no longer works chris1 2 2,192 Feb-06-2021, 07:59 AM
Last Post: chris1
  Code no longer working yk303 14 10,101 Dec-21-2020, 10:58 PM
Last Post: bowlofred
  UnboundLocalError: local variable 'figure_perso' referenced before assignment mederic39 2 2,266 Jun-11-2020, 12:45 PM
Last Post: Yoriz
  p]Why os.path.exists("abc/d") and os.path.exists("abc/D") treat same rajeev1729 1 2,161 May-27-2020, 08:34 AM
Last Post: DeaD_EyE
  local variable 'marks' referenced before assignment Calli 3 2,317 May-25-2020, 03:15 PM
Last Post: Calli

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020