python - Why is the name of the containing class not recognized as a return value function annotation? -


i going use python function annotations specify type of return value of static factory method. understand one of desired use cases annotations.

class trie:     @staticmethod     def from_mapping(mapping) -> trie:         # docstrings , initialization ommitted         trie = trie()         return trie 

pep 3107 states that:

function annotations nothing more way of associating arbitrary python expressions various parts of function @ compile-time.

trie valid expression in python, isn't it? python doesn't agree or rather, can't find name:

def from_mapping(mapping) -> trie:
nameerror: name 'trie' not defined

it's worth noting error not happen if fundamental type (such object or int) or standard library type (such collections.deque) specified.

what causing error , how can fix it?

pep 484 provides official solution in form of forward references.

when type hint contains names have not been defined yet, definition may expressed string literal, resolved later.

in case of question code:

class trie:     @staticmethod     def from_mapping(mapping) -> trie:         # docstrings , initialization ommitted         trie = trie()         return trie 

becomes:

class trie:     @staticmethod     def from_mapping(mapping) -> 'trie':         # docstrings , initialization ommitted         trie = trie()         return trie 

Comments

Popular posts from this blog

Delphi XE2 Indy10 udp client-server interchange using SendBuffer-ReceiveBuffer -

Qt ActiveX WMI QAxBase::dynamicCallHelper: ItemIndex(int): No such property in -

Enable autocomplete or intellisense in Atom editor for PHP -