Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

local variable 'type' referenced before assignment

Why I'm getting this error?

local variable 'type' referenced before assignment

Code:

try:
    if type(meeting.modified_date) != bool:
        //code

except Exception as e:
    raise ValidationError(_(str(e)))

finally:
    type = None
    if 1:
        type = 'auto'
    else:
        type = 'manual'

I was thinking some local variable creating this error but after debugging I come to know that this if condition creating an error because of this type().

like image 676
Adam Strauss Avatar asked Oct 17 '25 06:10

Adam Strauss


1 Answers

The reason you are getting this error is because you assign the global function type to a value in your code. If you do this, then the global function type will be overwritten to be a variable even before the actual assignment in the scope of the name space. Because the python interpreter now treats type as a local variable instead of the global function it is not assigned when you try to call the global function (which is treated as a local variable).

Solution: do not assign names of global functions to variables and rename the variable "type" to something else e.g., object_type.

I mean the code example is basically provided by @Paxmees in the replies. His explanation is a bit difficult to understand. But if you want to see one:

def example_error(var):
    if type(var) == bool:
        pass
    #this produces the error, because you overwrite global function type
    type = "string"

def example_fixed(var):
    if type(var) == bool:
        pass
    #fixed do not overwrite global function type:
    type_of_var = "string"
like image 84
tensulin Avatar answered Oct 20 '25 00:10

tensulin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!