Argh!! Can't wrap my head around this Python stuff!

nospam.Peter Otten __peter__ at web.de
Sat Nov 25 18:33:00 EST 2017


Greg Tibbet wrote:

>
> I'm an old timer, have programmed in Fortran, C, C++, Perl, and a bit
> of Java and trying to learn this new-fangled Python language!
>
> I've got a small program that uses PIL to create an image, draw some
> primitives (rectanges, ellipses, etc...) and save it.  Works fine...
> no issues.
>
> I've found in the past, the best way to "really learn" the language
> was to "dig into the guts" and understand it,.. I thought I was making
> progress, but when looking into the PIL library to see what's going on
> behind the scenes, I find the following code in ImageDraw.py
>
> def ellipse(self, xy, fill=None, outline=None):
>         """Draw an ellipse."""
>         ink, fill = self._getink(outline, fill)
>         if fill is not None:
>             self.draw.draw_ellipse(xy, fill, 1)
> <...snipped...>
>
> ellipse() uses the method  self.draw.draw_ellipse()   Okay, fine...
> but WHERE is draw_ellipse defined??  What magic is happening there?
> I've searched the entire PIL directory tree, and the ONLY two places
> draw_ellipse is mentioned are right there in the ellipse() function...
> WHAT am I missing??

The first argument of ellipse(), self is a strong hint that it is a method. If
you look into ImageDraw.py, located at

>>> import PIL.ImageDraw
>>> PIL.ImageDraw.__file__
'/usr/lib/python3/dist-packages/PIL/ImageDraw.py'

on my machine, you'll find the class of the same name, ImageDraw, and in its
initializer there's an assignment to the self.draw attribute:

        self.draw = Image.core.draw(self.im, blend)

Image is another module

>>> PIL.ImageDraw.Image
<module 'PIL.Image' from '/usr/lib/python3/dist-packages/PIL/Image.py'>

and if you look for the name 'core' in that module you'll find

    from PIL import _imaging as core

>>> PIL.ImageDraw.Image.core
<module 'PIL._imaging' from '/usr/lib/python3/dist-
packages/PIL/_imaging.cpython-34m-x86_64-linux-gnu.so'>

That would be the right time to say "Argh" with any number of exclamation marks
 for those who don't know C, but since you are familiar with that language
there's nothing to stop you from downloading the PIL (or rather the pillow)
source and look into the implementation. Once you have the complete code

https://pypi.python.org/pypi/Pillow/4.3.0
https://python-pillow.org/
https://github.com/python-pillow/Pillow
$ git clone https://github.com/python-pillow/Pillow.git

...you can use traditional tools:

$ find Pillow/ -name \*.c -print0 | xargs -0 grep draw_ellipse
Pillow/_imaging.c:_draw_ellipse(ImagingDrawObject* self, PyObject* args)
Pillow/_imaging.c:    {"draw_ellipse", (PyCFunction)_draw_ellipse, 1},

Rinse and repeat ;)




More information about the Python-list mailing list