Sunday, October 30, 2022

Everything you need to know about Python Magic



### Most built-in operations resolve to calling the "double underline" functions.

### -----------------------------------------------------------------------------


>>> x=3


>>> type(x)

<class 'int'>


>>> dir(x)

['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'as_integer_ratio', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']



### equal-to and less-than using the syntax and the Magic

### -----------------------------------------------------


>>> print(x==4, x < 4)

False True


>>> print(x.__eq__(4), x.__lt__(4))

False True



### The magic behind iterators

### --------------------------


>>> x=[1,2,3]

>>> type(x)

<class 'list'>

>>> dir(x)

['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']


### Iterate using the syntax

### ------------------------


>>> for i in x: print(i)

... 

1

2

3


### Iterate using the Magic

### -----------------------


>>> it = x.__iter__()

>>> type(it)

<class 'list_iterator'>

>>> dir(it)

['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__length_hint__', '__lt__', '__ne__', '__new__', '__next__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__']



>>> it.__next__()

1

>>> it.__next__()

2

>>> it.__next__()

3

>>> it.__next__()

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

StopIteration

>>>