Student Login

Hidden meaning of "("

Do you know about __call__?

This is a special method you can define on your Python class. It's optional. But def'ing it lets you hook into Python's function call syntax.

Let me explain. Look:

  1. class Prefixer:
  2. def __init__(self, prefix):
  3. self.prefix = prefix
  4. def __call__(self, message):
  5. return self.prefix + message

You use it like this:

  1. >>> simonsays = Prefixer("Simon says: ")
  2. >>> simonsays("Get up and dance!")
  3. 'Simon says: Get up and dance!'

What's the type of "simonsays"?

If you look at just that last line of Python code, you'd think it's a function. But it's not. It's an instance of Prefixer.

You with me so far?

Essentially, there's a translation step. When you write "simonsays('Shake it, baby!')", that's translated, in a sense, to "simonsays.__call__('Shake it, baby!')". In other words, "simonsays(" triggers a function call.

Also - check this out:

  1. >>> def increment(x):
  2. ... return x + 1
  3. ...
  4. >>> increment.__call__(2)
  5. 3

Surprise! Regular Python functions do this too!

What I want you to get is the difference between the python code you write, and what Python's runtime actually perceives.

When you write "something", followed by "(", Python itself processes that as "something.__call__(". No matter what "something" actually is.

This is a hint of what I mean by "seeing into the Matrix of Python".

You're starting to see what Python's runtime sees. Not just the Python code itself. Beneath that. To a level 99% of Python developers never realize is even there.

That's a FUN place to be. Pythonically dodging bullets and walking through walls. So to speak.

White Paper Bootcamp