A technique found in a certain OSS.
bs = BookShelf('Introduction to XX', 'First time YY', 'ZZ I can't hear anymore')
bs.map_(lambda: print(this))
stdout
Introduction to XX
First time YY
ZZ I can't hear anymore
This that suddenly appeared. Where did it come from?
I was working on it before calling the callback.
class Book:
    def __init__(self, name):
        self._name = name
        
    def __str__(self):
        return self._name
class BookShelf:
    def __init__(self, *book_names):
        self._books = [*map(Book, book_names)]
    
    def map_(self, callback):
        for book in self._books:
            callback.__globals__['this'] = book
            callback()
        
        del callback.__globals__['this']
It's not a big deal if you understand it, I was worried for a while because I doubted the extension of the interpreter and IDE.
I think it's Pythonic to pass it as an argument as follows.
class BookShelf:
    def __init__(self, *book_names):
        self._books = [*map(Book, book_names)]
    
    def map_(self, callback):
        for book in self._books:
            callback(book)
bs = BookShelf('Introduction to XX', 'First time YY', 'ZZ I can't hear anymore')
bs.map_(lambda this: print(this))
I want to take good care of Zen of Python.
Explicit is better than implicit. It is better to clarify than to imply.
** Reference **: Qiita --The Zen of Python
Recommended Posts