Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

type hint returns NameError: name 'datetime' not defined

I have this function below;

def time_in_range(start, end, x):
    """Return true if x is in the range [start, end]"""
    if start <= end:
        return start <= x <= end
    else:
        return start <= x or x <= end

The function parameters are all datetime type. I want to add typing hint to the function. This is what I did;

def time_in_range(start: datetime, end: datetime, x: datetime) -> bool:
    """Return true if x is in the range [start, end]"""
    if start <= end:
        return start <= x <= end
    else:
        return start <= x or x <= end

I get the error NameError: name 'datetime' is not defined. What is the proper way to add typing for this function?

I am using python v3.7

like image 949
user3848207 Avatar asked Sep 30 '19 13:09

user3848207


2 Answers

You need to import datetime, or use a string (remember, it is just an hint).

>>> def f(x: datetime):
...     pass
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'datetime' is not defined
>>> def f(x: 'datetime'):
...     pass
...
>>>
>>> from datetime import datetime
>>> def f(x: datetime):
...     pass
...
>>>

Python 3.7.4

like image 135
Pedro Rodrigues Avatar answered Oct 04 '22 04:10

Pedro Rodrigues


Either import datetime and use datetime.datetime as hint, or from datetime import datetime and use datetime as hint.

like image 21
blue_note Avatar answered Oct 04 '22 03:10

blue_note