简体   繁体   English

python 类型提示可从某些模块/子类调用

[英]python type hinting callable from certain modules / subclasses

I can use Callable to type hint that a parameter is a function itself:我可以使用Callable来输入参数是 function 本身的提示:

from typing import Callable
def myfun(f: Callable):
    pass

Could I somehow specify that the Callable should be from, eg pandas.DataFrame.agg (eg sum )?我能否以某种方式指定Callable应该来自,例如pandas.DataFrame.agg (例如sum )? Is this (not) recommended?这是(不)推荐的吗?

If you want to hint the function users to use a certain subset of known functions, I would suggest to use directly an Enum of callables.如果您想提示 function 用户使用已知函数的某个子集,我建议直接使用可调用的Enum

Something like this:像这样的东西:

from enum import Enum
import pandas as pd 


class FunctionAllowed(Enum):

    agg = pd.DataFrame.agg
    sum = pd.DataFrame.sum


def myfun(f:FunctionAllowed):
    a = pd.DataFrame()

    f.value(a)

myfun(FunctionAllowed.sum)

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

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