pythonpython-3.xtime

Error says "local variable 'time' referenced before assignment" but I'm not using a variable called time


I'm trying to run a code, but Python is telling me that local variable 'time' referenced before assignment. This is the code:

from enlace import *
from time import time
import numpy as np

imageW = "./img/transmission_receive.png"

def process_time(time, unit):
    units={"ms":1e3, "μs": 1e6, "ns":1e9}
    return units.get(unit)*time, unit

def main():
    try:
        door="COM6"
        com2 = enlace(door)

        com2.enable()
    
        start_time = time()

        img_size_b, nRx = com2.getData(4)
        img_size=int.from_bytes(img_size_b, 'big')
        rxBuffer, nRx = com2.getData(img_size)
    
        time_to_receive=time() - start_time
        time, unit=process_time(time_to_receive, 'ms')
    
        answer=nRx.to_bytes(4, 'big')
        com2.sendData(answer)
    
        with open(imageW, 'wb') as f:
            f.write(rxBuffer)
       
        print("-------------------------\nMessage sent.\n-------------------------")
        print(f"Program took {time} {unit} to receive.")
        print(f"Message received at {size/time_to_receive} bytes/s.")
    
    except Exception as e:
        print(e)
        com2.disable()
    

if __name__ == "__main__":
    main()

The particular line giving me trouble right now is the start_time = time() one, to which Python says local variable 'time' referenced before assignment, which I don't understand, since I'm creating the variable start_time which uses the time() function from the time library.

Traceback (most recent call last):
  File "d:\Insper\CamFis\Projeto 2\server.py", line 46, in <module>
    main()
  File "d:\Insper\CamFis\Projeto 2\server.py", line 19, in main
    start_time = time()
UnboundLocalError: local variable 'time' referenced before assignment

Solution

  • I think your problem is that you are using the time.time() function and a variable called time. In python functions are first-class-objects. Means time.time() is treated in a similar way as your variable time. time.time() is then overwritten by your variable time. Try this in a python console:

    >>> from time import time
    >>> time
    >>> time()
    >>> time = time()
    >>> time
    >>> time()
    

    Problem should be fixed by renaming the varibale time or import time.time() as from time import time as gettime or something similar.