카테고리 없음

Python: First-class functions 1

focalpoint 2022. 3. 24. 10:37

 

1. User defined Callable Object

User defined callable object can be defined as below. Magic method __call__ should be implemented.

import random

class BingoCage:

    def __init__(self, items):
        self.__items = list(items)
        random.shuffle(self.__items)

    def __pick(self):
        try:
            return self.__items.pop()
        except IndexError:
            raise LookupError('pick from empty BingoCage')

    def __call__(self):
        return self.__pick()

bingo = BingoCage(range(3))
bingo()
bingo()
bingo()

 

2. Inspect, Signature

signature object is used to inspect function objects' parameters.

signature object's bind method is to check whether the given parameters are valid for a certain function.

from inspect import signature

def func(param1:str, param2:'int > 0'=3, param3='hello world') -> str:
    return param1 + str(param2) + param3

sig = signature(func)
for name, param in sig.parameters.items():
    print(name, param.default)

param_dict1 = {
    'param1': 'what?',
}
b1 = sig.bind(**param_dict1)
print(b1)

param_dict2 = {
    'param1': 'what?',
    'noparam': 3
}
b2 = sig.bind(**param_dict2)
print(b2)

 

3. Operators

1) basic operators 

from functools import reduce
from operator import mul

def fact(n):
    return reduce(mul, range(1, n+1))

print(fact(5))

2) itemgetter()

from operator import itemgetter

metro_data = [
    ('Seoul', 'South Korea'),
    ('Tokyo', 'Japan'),
    ('WS', 'US'),
]

for city in sorted(metro_data, key=itemgetter(1)):
    print(city)

city_name = itemgetter(0)
for row in metro_data:
    print(city_name(row))

3) attrgetter()

from collections import namedtuple
from operator import attrgetter

Person = namedtuple('Person', 'name age sex occupation')

p1 = Person('morgan', 28, 'm', 'engineer')

ag1 = attrgetter('name', 'occupation')
print(ag1(p1))

 

4. functools partial

functools.partial() is a high order function that creates a callable with given parameters.

from functools import partial

def power(n, exponent):
    return n**exponent

square = partial(power, exponent=2)
print(square(3))