Question

When using the thumbnail() method in the Pillow (PIL) module, the following convention must be observed where two sets of (nested) parenthesis are used:

pil_image.thumbnail((128,128))

If only one set is used, Python generates the following error:

TypeError: 'int' object is not subscriptable

Does the inner-most parentheses have a formal name?

PS: Following also works:

box = 128, 128 # No parentheses needed.
pil_image.thumbnail(box)

Also: Is it a deficiency on part of the Python parser to not be able to figure out the intention here?

Was it helpful?

Solution 2

The fact the the parenthesis` are nested has nothing to do with anything.

It is the , (comma) that is important. Which is why box = 128, 128 works and whose end result is the equivalent of box = (128, 128)

>>> box = 128, 128
>>> box
(128, 128)
>>> box = (128, 128)
>>> box
(128, 128)

For example, in python:

>>> myvar = ((128))
>>> myvar
128

but

>>> myvar = ((128),)  # notice the COMMA
>>> myvar
(128,)

(128,) is called a tuple which is something like a LIST (mylist = [])

One of the main differences is a LIST can be modified, a tuple cannot:

e.g.

mylist.append(1)  # works
myvar.append(1)  # fails

OTHER TIPS

You are passing a tuple to the thumbnail() method. The distinction is as follows:

thumbnail((128,128))  # single tuple argument: (128,128)

thumbnail(128,128)    # two integer arguments: 128 and 128

Your box variable is also a tuple, which is why it works as well:

>>> box = 128, 128
>>> box
(128, 128)
>>>
>>> type(box)
<type 'tuple'>

Its called a tuple. See this link on tuples and other sequence types.

thumbnail is a function that takes a tuple as its first argument. When you do thumbnail(128, 128), python tries to treat 128 as a tuple (by indexing it), which it isn't, and so you get your error.

In the case of variable assignment like box = 128, 128, python understands that box is meant to be a tuple, but in the context of thumbnail(128, 128), python assumes you meant to pass in two int arguments, and not a single tuple.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top