Python 3 type hinting at None?

def foo( hello: str='world', bar: str=None, another_string_or_None: str|????=None): pass 

I'm trying to set a type hint in Python in a function, you can add some type hints with something: str|bool='default value' , but which type hints at None ?: /

+6
source share
2 answers

In your example:

 def foo( hello: str='world', bar: str=None, another_string_or_None: str|????=None): ... 

I noticed that your use case is "something or not."

Starting with version 3.5, Python supports type annotations through the typing module . And in your case, the recommended annotation method is to use the typing.Optional[something] hint . This makes the exact meaning you are looking for.

So the hint for another_string_or_None will be:

 import typing def foo( hello: str='world', bar: str=None, another_string_or_None: typing.Optional[str]=None): ... 
+7
source

It's just None !

 >>> def nothing(nun: None) -> None: ... return nun ... >>> nothing(None) >>> 

Or at least it could be.

Since these annotations are not relevant to Python outside of / the correct syntax, this is similar to tools.

If you use typecheck-decorator , then you will need to use type(None) :

 >>> import typecheck as tc >>> >>> @tc.typecheck >>> def nothing(nun: type(None)) -> type(None): ... return nun ... >>> nothing(None) >>> nothing(0) typecheck.framework.InputParameterError: nothing() has got an incompatible value for nun: 0 >>> nothing(False) typecheck.framework.InputParameterError: nothing() has got an incompatible value for nun: False 

Typecheck also allows you to more clearly "add more than one type of hint" using tc.any() (OR), tc.all() (AND) and, moreover, moreover.

Beware that tc.none() is a NAND-like predicate; not what you are looking for - with no arguments, it will accept any type equivalent to tc.all() or more apt tc.anything .

0
source

Source: https://habr.com/ru/post/955320/


All Articles