2
votes

I can't get typing hinting for return types to generate any warnings. For example the following code generates no warnings:

def foo():
    """
    :rtype : bool
    """
    return "bar"    # Returning wrong type

x, y = foo()        # Incorrectly expecting tuple

Do return types generate warnings, or are they only used for code completion? Type warnings when using type hinting for function parameters is working as expected. Python is 2.7, PyCharm is 4.5.3.

2
I believe it's only for code completion.f.rodrigues
You miss warnings. Where should these warnings be emitted? Should python emit them? Or do you want pyCharm to emit them?guettli
@f.rodrigues - Thanks for the confirmationstdout

2 Answers

3
votes

You can use -> to hint the return type like this:

def hello(name: str) -> str:
    return 'hello '+name

Type hints are just hints that help IDE. Those types are not enforced. You can add a hint for a variable as str and set an int to it like this:

a:str = 'variable hinted as str'
a = 5  # See, we can set an int 

PyCharm will warn you but you will still be able to run the code. Because those are just hints. Python is not a type strict language. Instead, it employs dynamic typing.

0
votes

Return types are only used for code completion, what you've done has thoroughly confused PyCharm as to what you actually want to return.

Furthermore, x,y = <string> is valid if string is 2 characters long, so your last statement is not an invalid one.

In[3]: x, y = "ac"
In[4]: x
Out[4]: 'a'
In[5]: y
Out[5]: 'c'