Skip to content

Add _normalize_coords() to reduce duplicate code - #9899

Open
radarhere wants to merge 1 commit into
python-pillow:mainfrom
radarhere:normalize
Open

Add _normalize_coords() to reduce duplicate code#9899
radarhere wants to merge 1 commit into
python-pillow:mainfrom
radarhere:normalize

Conversation

@radarhere

Copy link
Copy Markdown
Member

Extracting a cleanup idea from #9490

Co-authored-by: Krishna Chaitanya Balusu <krishnabkc15@gmail.com>
Comment thread src/PIL/ImageDraw.py
ellipse_xy = (xy[0] - radius, xy[1] - radius, xy[0] + radius, xy[1] + radius)
self.ellipse(ellipse_xy, fill, outline, width)

def _normalize_coords(self, xy: Coords) -> Sequence[Sequence[float]]:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should maybe be a free function in the module?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why? It's not used anywhere else.

@akx akx Aug 25, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since it doesn't need to be overridden by any subclass of ImageDraw I can conceive of, and free functions are a tiny bit faster to call:

In the disassembly for a quick timing example,

  • a free function call is LOAD_GLOBAL (looks at the module globals table) + LOAD_FAST_BORROW for the argument + CALL
  • an instance function call is LOAD_FAST_BORROW for the local self + LOAD_ATTR (a dict lookup on the instance) + LOAD_FAST_BORROW for the argument + CALL

So in other words, because it's unnecessary to be an instance method.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My personal preference would be for code that is only called from internal methods in the instance to be a method, as an indicator of how it is used. It also places it much closer to the first self._normalize_coords(xy), making it quicker to understand.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants