简体   繁体   中英

How to type-hint non-basic parameters of a function?

In python3.6

Suppose you have a function that has 5 arguments. A a string object, a list of string objects, argparse.Namespace object, a pandas dataframe, and a logging.Logger object.

Such as

def main(a_string, a_list, args, df, logger):

The first two are pretty straight forward, but how do you cast the last 2?

def main(a_string: str, a_list: List[str], args: ???, df: ???, logger: ???) -> str:

Thanks in advance!

for reference: 
type(args) -> argparse.Namespace 
type(logger) -> logging.Logger

If I understand your question correctly, it's the same as for str (a type), ie enter the type:

def main(a_string: str, a_list: List[str], args: argparse.Namespace df: pandas.DataFrame, logger: logging.Logger) -> str:

Though I generally refactor to avoid long arg lists. I'm not a fan of having line breaks in my function signatures.

If you need to find the type(s) of an object:

>>> type(logging.root)
logging.RootLogger
>>> type(logging.root).__bases__
(logging.Logger,)

As Kache typed earlier, that should be the right answer, but you must be concerned of two things when doing that stuff:

  1. First of all, Python is type hinted (if you want to read more, please, go here ).
  2. This type hinting will not raise any exception directly if one of the aruguments of the method does not satisfy the type of that variable. It will raise exception only when you try to use a method from that supposed type. For instance, suppose your a_string is not really a str and inside your function you are calling a simple a_string.strip(). That will raise an exception.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM