简体   繁体   English

如何键入提示 function 的非基本参数?

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

In python3.6在python3.6

Suppose you have a function that has 5 arguments.假设您有一个具有 5 个 arguments 的 function。 A a string object, a list of string objects, argparse.Namespace object, a pandas dataframe, and a logging.Logger object. 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:如果我正确理解了您的问题,则与str (类型)相同,即输入类型:

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.虽然我通常会重构以避免长 arg 列表。 I'm not a fan of having line breaks in my function signatures.我不喜欢在我的 function 签名中出现换行符。

If you need to find the type(s) of an object:如果您需要查找 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:正如 Kache 之前键入的那样,这应该是正确的答案,但是在做这些事情时你必须关注两件事:

  1. First of all, Python is type hinted (if you want to read more, please, go here ).首先,Python 是类型提示的(如果您想了解更多信息,请在此处阅读 go)。
  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().例如,假设您的 a_string 不是真正的 str,并且在您的 function 中,您正在调用简单的 a_string.strip()。 That will raise an exception.这将引发异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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