Ayrat
Ayrat

Reputation: 1259

C# like extension functions in python?

End up writing lots of:

lines = [l.strip() for l in lines]

Is there a readable Pythonista way to do it like: lines.stripped() that returns lines stripped? (in C# you could add an 'extension method' to a list of strings).

Upvotes: 1

Views: 2404

Answers (2)

GravityWell
GravityWell

Reputation: 1567

There is https://github.com/clarete/forbiddenfruit

Wether you consider it readable Pythonista is personal choice. But it does work.

I do wish Python had something like CSharp, Kotlin, Scala, Ruby "Extension Methods". Until then forbiddenfruit or the technique it uses (which can be simplified significantly) is the only way I know.

Upvotes: 2

Devin Jeanpierre
Devin Jeanpierre

Reputation: 95536

No, you can't monkeypatch the list type. You can create a subclass of list with such a method, but this is probably a poor idea.

The Pythonic way to capture oft-repeated bits of code is to write a function:

def stripped(strings):
    return [s.strip() for s in strings]

Upvotes: 5

Related Questions