UnboundLocalError: local variable … referenced before assignment

前端 未结 2 1740
时光说笑
时光说笑 2020-12-11 06:24
import hmac, base64, hashlib, urllib2
base = \'https://.......\'

def makereq(key, secret, path, data):
    hash_data = path + chr(0) + data
    secret = base64.b64d         


        
相关标签:
2条回答
  • 2020-12-11 06:44

    You are redefining the hmac variable within the function scope, so the global variable from the import statement isn't present within the function scope. Renaming the function-scope hmac variable should fix your problem.

    0 讨论(0)
  • 2020-12-11 06:56

    If you assign to a variable anywhere in a function, that variable will be treated as a local variable everywhere in that function. So you would see the same error with the following code:

    foo = 2
    def test():
        print foo
        foo = 3
    

    In other words, you cannot access the global or external variable if there is a local variable in the function of the same name.

    To fix this, just give your local variable hmac a different name:

    def makereq(key, secret, path, data):
        hash_data = path + chr(0) + data
        secret = base64.b64decode(secret)
        sha512 = hashlib.sha512
        my_hmac = str(hmac.new(secret, hash_data, sha512))
    
        header = {
            'User-Agent': 'My-First-test',
            'Rest-Key': key,
            'Rest-Sign': base64.b64encode(my_hmac),
            'Accept-encoding': 'GZIP',
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    
        return urllib2.Request(base + path, data, header)
    

    Note that this behavior can be changed by using the global or nonlocal keywords, but it doesn't seem like you would want to use those in your case.

    0 讨论(0)
提交回复
热议问题