Implement method chain in Python

Q. Do you want to implement a method chain easily?

A. Yes.

Implementation

class MyList(list):
    ...


def method(defined_type):
    def wrap(f):
        def wrapper(*args, **kwargs):
            return defined_type(f(*args, **kwargs))
        return wrapper

    def decorator(f):
        setattr(defined_type, f.__name__, wrap(f))

    return decorator


@method(MyList)
def map(l, func):
    return [func(el) for el in l]

print(MyList([1, 2, 3]).map(lambda x: x+1).map(lambda x: x+2)) # [4, 5, 6]

Recommended Posts

Implement method chain in Python
Implement Enigma in python
Implement recommendations in Python
Implement XENO in python
Simplex method (simplex method) in Python
Private method in python
Implement sum in Python
Implement Traceroute in Python 3
Implement naive bayes in Python 3.3
Implement ancient ciphers in python
Implement Redis Mutex in Python
Implement extension field in Python
Implement fast RPC in Python
Implement Dijkstra's Algorithm in python
Implement Slack chatbot in Python
Suppressing method overrides in Python
Implement stacking learning in Python [Kaggle]
Try implementing extension method in python
Implement the Singleton pattern in Python
Implemented label propagation method in Python
Simulate Monte Carlo method in Python
Hash method (open address method) in Python
Quickly implement REST API in Python
Quadtree in Python --2
Python in optimization
CURL in python
I tried to implement PLSA in Python
Metaprogramming in Python
Python 3.3 in Anaconda
Geocoding in python
SendKeys in Python
Implement __eq__ etc. generically in Python class
I tried to implement permutation in Python
Meta-analysis in Python
Unittest in python
Markov chain transition probability written in Python
Electron Microscopy Simulation in Python: Multislice Method (1)
Collectively implement statistical hypothesis testing in Python
I tried to implement PLSA in Python 2
Epoch in Python
Discord in Python
Sudoku in Python
DCI in Python
quicksort in python
nCr in python
Electron Microscopy Simulation in Python: Multislice Method (2)
Plink in Python
I tried to implement ADALINE in Python
Constant in python
I tried to implement PPO in Python
Lifegame in Python.
FizzBuzz in Python
Sqlite in python
StepAIC in Python
N-gram in python
LINE-Bot [0] in Python
Csv in python
Disassemble in Python
Reflection in Python
Constant in python
nCr in Python.