Home > OS >  Static typing not working when printing the "type()" function
Static typing not working when printing the "type()" function

Time:10-17

This issue came across when I was trying to statically type Python like this:

maybeFloat: float = 2

But when I'm trying to print the type of the variable doing this:

print(type(maybeFloat))

The console logs this:

<class 'int'>

What am I doing wrong? What's the purpose of static typing in Python if it is not going to work?

CodePudding user response:

Indeed there is no such thing as static typing in python. var : int = 1 is an annotation. Something only useful as documentation.

Even you can assign any type to a typed variable :

x float = 'I am a float!'

Also the the 'types' does not need to be types:

x: 'hello' # x is a 'hello'

Annotations reside in the __annotations__ variable. So you can use it as a namespace to hold variables

x: 3.14
print(__annotations__[x]) # -> 3.14

Thats not very useful though

  • Related