Instructing a function to be called with a specific argument without executing it

前端 未结 2 1444
隐瞒了意图╮
隐瞒了意图╮ 2021-01-24 12:44

I am trying to encode logic to filter a Pandas dataframe. I\'d like to encode the logic as a dictionary, with the subgroup name as the key, and the function to filter for the su

相关标签:
2条回答
  • 2021-01-24 13:39

    You can consider functools.partialmethod, which allows you to specify any number of args or kwargs:

    from functools import partialmethod
    
    mappings = {'Jets Fans': partialmethod(BaseFilter.for_jets_fans, 'Jets'),
                'Patriots Fans': partialmethod(BaseFilter.for_patriots_fans, 'Patriots'),
                'NFC Fans': partialmethod(BaseFilter.for_team_fans, 'Bears', 'Packers')}
    
    0 讨论(0)
  • 2021-01-24 13:40

    If BaseFilter.for_team_fans is the common base function for every entry in your analytics_table_mappings dict, then you can factor it out. Since that leaves only one property, the dict could be reduced to a simple key: args pairing, such as

    analytics_table_mappings = {
        "Jets Fans": "Jets",
        "Patriots Fans": "Patriots",
        "NFC Fans": ["Bears", "Packers", ...]
    }
    

    and then maybe incorporate the logic into a simple class:

    class Teams:
        analytics_table_mappings = {
            "Jets Fans": "Jets",
            "Patriots Fans": "Patriots",
            "NFC Fans": ["Bears", "Packers", ...]
        }
    
        @classmethod
        def get_teams(cls, fan_type):
            if fan_type not in cls.analytics_table_mappings:
                return 'Invalid fan type: {}'.format(fan_type)
            teams = cls.analytics_table_mappings[fan_type]
            if not isinstance(teams, list):
                teams = [teams]
            return [cls.for_team_fans(team) for team in teams]
    
        def for_team_fans(team_name):
            # your logic here
            return team_name
    
    
    print(Teams().get_teams("Jets Fans"))
    >> ['Jets']
    
    print(Teams().get_teams("Patriots Fans"))
    >> ['Patriots']
    
    print(Teams().get_teams("NFC Fans"))
    >> ['Bears', 'Packers', ...]
    
    print(Teams().get_teams("Argonauts Fans"))
    >> Invalid fan type: Argonauts Fans
    
    0 讨论(0)
提交回复
热议问题