The classical "callable" is a function, but in #Python classes are also callables.
In many programming languages (e.g. JS, PHP, C++) creating a new "instance" of a class (an object whose type is that class) involves the "new" keyword:
let eol = new Date(2020, 1, 1);
But in #Python to make a new class instance we just call the class:
eol = date(2020, 1, 1)
The fact that classes are callables means the distinction between a function and a class is often quite subtle. All of these "functions" are actually implemented as classes:
n = float("4.5")
m = int(n)
s = str(m)
b = bool(m)
t = tuple('abcd')
e = enumerate(t)
r = reversed(t)
When you call a function, you get the return value of that function.
When you call a class, you get back an "instance" of that class.
class Thing:
def __init__(self, name): self.name = name
thing = Thing() # Thing instance
"Function" is a fuzzy term in the Python world because we often use it to refer to non-functions.
The phrases "the reversed function" or "the int function" might be technically incorrect but colloquially they're a-okay.
Need to split up seconds into hours, minutes, & seconds in #Python?
This is one of the rare instances in which I might reach for Python's built-in divmod function. Though datetime.timedelta might work too, depending on your use case.
Let's compare int, //, divmod, & timedelta🧵
Given a number of seconds:
>>> duration = 4542
You might have thought to use division, modulo, and Python's int function 🤔
Python's "for" loops are single-purposed: they can loop over an iterable item-by-item. That's it.
The "for" loop itself can't loop in reverse or loop over multiple iterables.
For this reason, looping helpers are a VERY big deal in #Python.
Let's talk about looping helpers. 🧵
Want to loop over an iterable in the reverse direction? If it's a reversible iterable (lists, tuples, dictionaries, etc), you can use the reversed helper:
>>> colors = ["pink", "blue", "green"]
>>> for color in reversed(colors):
... print(color)
...
green
blue
pink
Note that the "for" loop isn't reversing here: reversed is!
The built-in reversed function accepts an iterable and returns a lazy iterable that provides each item from the original iterable in the reverse order.
>>> r = reversed(colors)
>>> next(r)
'green'
>>> next(r)
'blue'