Finding a function parameter's methods/attributes

I'm working on a project and I'm reading through the code, but whenever I see a function parameter I have no idea what kind of object it is. I come from a strong Java background, so this notion of not knowing what a parameter is is very confusing to me. What would be the pythonic way of wrapping my head around this?

Posted Sep 24, 2018, 4:23 AM UTC

102
novel_yet_trivial•

Python generally uses "duck typing". That is, if the function needs a duck, and whatever it gets quacks, that's good enough. No need to verify or care if it actually is a duck.

Or in real code:

def square(x):
    '''return the square'''
    return x**2

The code does not care if you pass an int, float, long, complex or some custom object. If you pass something that can't be squared like a string, it throws an error.

I know this does not help you, but I hope it explains why there is no easy way to find the type.

That said, newer code should have type hinting, which is a basically a standardized commenting system to declare types, and those show up in the help.

6
Diapolo10Diapolo10•

Type hints are your friend.

def some_function(x: int, y: int) -> int:
    return x + y

def another_func(stuff: str, things: bool):
    print(stuff * things)

And for data structures, there's the typing module:

from typing import List

def list_to_string(lst: List[str]) -> str:
    return " ".join(lst)
2