36

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

2 Answers 2

50

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

--

UPDATE. For a slightly different version of this issue import __future__.annotations

from __future__ import annotations

def f(dto: Dto):
    pass

class Dto:
    pass

This would otherwise fail in the function reference to the Dto class. Python4 will have this as the default behaviour. For now, the import must be the first statement of the file.

Tested in Python 3.8.10.

See: https://peps.python.org/pep-0563/

23

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

2
  • from datetime import datetime worked for me
    – Sameen
    Feb 16 at 17:03
  • 1
    @Sameen yes, both are equivalent, there's a datetime object inside another module named datetime
    – blue_note
    Feb 17 at 12:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.