Syntax of the Python type() function The type() function is used to get the type of an object. When a single argument is passed to the type() function, it returns the type of the object. Its value is the same as the object.
Type annotations — also known as type signatures — are used to indicate the datatypes of variables and input/outputs of functions and methods. In many languages, datatypes are explicitly stated. In these languages, if you don't declare your datatype — the code will not run.
First, annotations can be fully implemented as decorators. You can just define an @annotate decorator and have it take an argument name and a Python expression as arguments and then store them in the target function's annotations attribute. This can be done for Python 2 as well.
I was going to use Python function annotations to specify the type of the return value of a static factory method. I understand this is one of the desired use cases for annotations.
class Trie:
@staticmethod
def from_mapping(mapping) -> Trie:
# docstrings and initialization ommitted
trie = Trie()
return trie
PEP 3107 states that:
Function annotations are nothing more than a way of associating arbitrary Python expressions with various parts of a function at compile-time.
Trie
is a valid expression in Python, isn't it? Python doesn't agree or rather, can't find the name:
def from_mapping(mapping) -> Trie:
NameError: name 'Trie' is not defined
It's worth noting that this error does not happen if a fundamental type (such as object
or int
) or a standard library type (such as collections.deque
) is specified.
What is causing this error and how can I fix it?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With