(Bad) practice of using this in Python

Overview

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?

Reveal

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.

Why I think it's a bad practice

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

(Bad) practice of using this in Python
Meaning of using DI framework in Python
Summary of Excel operations using OpenPyXL in Python
Basics of I / O screen using tkinter in python3
Equivalence of objects in Python
python: Basics of using scikit-learn ①
Introducing Python in Practice (PiP)
Implementation of quicksort in Python
Translate using googletrans in Python
Using Python mode in Processing
Ssh connection memo using ProxyCommand of ssh_config in Python
Applied practice of try/except and dictionary editing and retrieval in Python
A memo of writing a basic function in Python using recursion
Pixel manipulation of images in Python
GUI programming in Python using Appjar
Image capture of firefox using python
Precautions when using pit in Python
Division of timedelta in Python 2.7 series
Removal of haze using Python detailEnhanceFilter
MySQL-automatic escape of parameters in python
Handling of JSON files in Python
Try using LevelDB in Python (plyvel)
Implementation of life game in Python
Waveform display of audio in Python
Using global variables in python functions
This and that of python properties
Let's see using input in python
Infinite product in Python (using functools)
Implementation of desktop notifications using Python
Edit videos in Python using MoviePy
Law of large numbers in python
Implementation of original sorting in Python
Algorithm (segment tree) in Python (practice)
Reversible scrambling of integers in Python
Handwriting recognition using KNN in Python
Try using Leap Motion in Python
Depth-first search using stack in Python
When using regular expressions in Python
GUI creation in python using tkinter 2
Write various forms of phylogenetic tree in Python using ETE Toolkit
Mouse operation using Windows API in Python
Conversion of string <-> date (date, datetime) in Python
[Python] Extension using inheritance of matplotlib (NavigationToolbar2TK)
Notes using cChardet and python3-chardet in Python 3.3.1.
Automatic collection of stock prices using python
About building GUI using TKinter of Python
Try using the Wunderlist API in Python
GUI creation in python using tkinter part 1
Check the behavior of destructor in Python
Get Suica balance in Python (using libpafe)
Slowly hash passwords using bcrypt in Python
General Theory of Relativity in Python: Introduction
Try using the Kraken API in Python
Using venv in Windows + Docker environment [Python]
Output tree structure of files in Python
[Linux] List of Linux commands used in practice
Display a list of alphabets in Python 3
Comparison of Japanese conversion module in Python3
[FX] Hit oanda-API in Python using Docker
Python: Application of image recognition using CNN
Summary of various for statements in Python