简体   繁体   中英

Python: Referenced before assignment

I receive the following error local variable 'ticket_reservation_expired' referenced before assignment . Anyone knows how to resolve this?

I think a solution could be to assign ticket_reservation_expired = "" before calling the function, but I wonder if that is the best way to resolve this?

helpers.py

def ticket_reservation_expired(request, timestamp_of_reservation):
    """
    * Calculate the latest possible time where tickets are still reserved.
    * Check that 'created' timestamp of reservation item is not expired.
    * If expired, error message is being generated and redirect occurs.
    """
    latest_time_before_expired = timezone.now() - timedelta(
        minutes=settings.MINUTES_TICKET_RESERVATION
    )
    if timestamp_of_reservation < latest_time_before_expired:
        messages.add_message(
            request,
            messages.ERROR,
            _("Ticket reservation is too far in the past.")
        )
        return True

views.py

ticket_reservation_expired = ticket_reservation_expired(
    self.timestamp_of_reservation
)
if ticket_reservation_expired:
    return redirect(
        'events:detail',
        organizer=self.organizer,
        event=self.event,
    )

Your function only returns a value when a certain condition is met. When it is not met, nothing is returned. Good style is to either never return a value or always return one. Since if the condition is met you return True, return False when it is not met and your error should go away.

Also, in the code you posted, you named your variable and your function the same, this will lead you to no end of trouble.

The problem is if the function does not return anything then it will throw an error as the variable is never defined because initialization of variable depends on the return value of the function. Just initialize the variable with None

ticket_reservation_expired_var = None
ticket_reservation_expired_var = ticket_reservation_expired(
    self.timestamp_of_reservation
)
if ticket_reservation_expired_var:
    return redirect(
        'events:detail',
        organizer=self.organizer,
        event=self.event,
    )

What you can do is make that name a global reference inside the function:

global ticket_reservation_expired

That goes on the first line of the function. Alternatively, add another parameter to the function ticket_reservation_expired and just pass it in when you call the function so that the value is effectively 'transferred' to the function scope. However, changes to the variable will only take effect in the function's scope. So global is the option if you need to make any changes 'save' themselves after the function returns.

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