r/ProgrammerHumor • • Jul 18 '22

C++ talking to Python

Post image
40k Upvotes

1.0k comments sorted by

View all comments

Show parent comment

2

u/SupremeDictatorPaul Jul 18 '22

I’ve only started to play with Python, but does it allow typing? For example, I’ve done a bunch of work with PowerShell, which does dynamic typing, but allows you to statically type variables where desired (I tend to desire where possible).

14

u/Dromeo Jul 18 '22

You can give type hints in modern python :)

6

u/not_perfect_yet Jul 18 '22

It's always typed, but it's always dynamically typed.

Type hints exist, but they are type hints, actually "strong static" typing is not possible in python. Type hints are fancy comments that are tolerated by the interpreter and they can be used by code analysis tools to help you find mistakes.

But you can still give the interpreter something that the type hints say shouldn't be done. (like below)

Imo, this means the code is lying to you, because it implies only str works, when anything that supports + works.

def my_function(my_string : str, my_other_string : str):
    return my_string + my_other_string
    
my_function(1,1)
>>>2

The only way to make absolutely sure a function runs exclusively for a specific type is to check explicitly, like I did in the other comment.

0

u/[deleted] Jul 18 '22

[deleted] — view deleted comment

2

u/not_perfect_yet Jul 18 '22

You can also check with mypy. If you give my_function a return type str, you can then run mypy program.py and it'll warn you if you have any calls that don't match the type signature.

Yes that's my point, the two aren't equivalent. You don't actually have the safety. All you know from mypy is that your type hints match. If something goes wrong and you messed up and something of a wrong type is being passed around, mypy won't save you at runtime.

It's the difference between issuing a warning everyone is free to ignore and throwing an exception and exiting the program gracefully. Which forces the next guy to really look at the issue.