0

I encountered this way of declaring variable on internet but can't really see its effect

some_variable:str = 'abc'

it doesn't seem to change the data type as first guess.

test_var:str=1

The type of variable still int as test with

type(test_var)

what actually is this?

DUNGHT13
  • 41
  • 4

1 Answers1

1

This is "type checking". Its effectiveness will depend on your IDE's capabilities. It has nothing to do with runtime behaviour.

For example:

x:str = 0

The type hint suggests that x should only ever refer to a str type. However, here we assign zero (an int). At runtime the assignment will take place as written. However, your IDE may highlight a potential issue.

Type hinting has limited use in my opinion. Here's another example:

def afunc(s):
    i:str = s
    return i
def bfunc():
    return 0
    
afunc(bfunc())

In this case the variable i will be assigned int at runtime but the IDE cannot detect any potential problem. [caveat: Pylance in VSCode can't detect the problem. Other static type checkers may be more intelligent]

snakecharmerb
  • 47,570
  • 11
  • 100
  • 153
DarkKnight
  • 19,739
  • 3
  • 6
  • 22
  • They are also very useful for automatically generated documentation, and there are some CI/CD tools that make use of them as well – Alexander Dec 10 '22 at 08:57
  • Type hints can be very useful. Check out frameworks like fastAPI for elegant use of type hints https://fastapi.tiangolo.com/#recap – Carlos Horn Dec 10 '22 at 09:06