Python Core Syntax and the Magic Behind It! | by Arafath Hossain | Apr, 2022

Have you ever ever questioned how one can run operations like including (+) two numbers or strings in Python and but get affordable outcomes? On this article, we are going to get to know the reply and a some extra.

Picture by Sergi Viladesau on Unsplash

In Python, we will run operations like 1+2 or 'a' + 'b' and get outcomes of 3 and ab respectively. Or we will name features like len() on completely different knowledge constructions (Listing, Dictionary, Tuple, and Set) and get the overall variety of components as proven within the code block under.

# creating objects of various knowledge varieties for demo
l1 = [1, 2, 5]
d1 = "one": 1, "two":2t1 = (1, 2, 3)s1 = 1, "two"[len(i) for i in [l1, d1, t1, s1]]>> [3, 2, 3, 2]

These are some examples of Python core syntax. Another kinds of widespread Python core syntax are:

  • Frequent algebraic expressions e.g. +, -, *.
  • Frequent operators for comparability e.g. ==, <, in.
  • Constructed-in features e.g. len(), str().
  • Reflexion e.g. kind(), isinstance() and so forth.

The rationale that Python can perceive these core syntax is that anytime Python receives a core syntax it may possibly relate it to a selected technique that’s answerable for that particular syntax.

For instance, after we name one thing like 1+2, behind the scene, Python calls a technique referred to as __add__() or after we name len(), Python requires __len__() technique. Such strategies are referred to as magic strategies or particular function strategies. Checkout the next code block for a demo.

result1 = 'a' + 'b'print(f"Summing up a, b with `+` = result1")result2 = 'a'.__add__('b')print(f"Summing up a, b with `__add__()` = result2")>> Summing up a, b with `+` = ab
>> Summing up a, b with `__add__()` = ab

Discover, how we used the magic perform __add__() utilizing a dot notation. It is as a result of __add__() is a non-public technique that is already applied contained in the string class which is the category kind of our objects: a. We are able to additionally apply the dir() perform on a to take a look at the opposite strategies which might be already applied.

print(f"Class of `a` is = 'a'.__class__")print("nAll the strategies obtainable in `a`: ")print(dir('a'.__class__))>> Class of `a` is = <class 'str'>>> All of the strategies obtainable in `a`: 
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

The demonstration above reveals how for Python to perform correctly on the core syntax, the magic technique must be delivered by the lessons of the objects concerned within the operation. This additionally opens up the chance for us to implement magic strategies in our customized lessons.

For instance, let’s assume that we’re working for a trucking firm that carries vehicles. To supply a fast verify on the overall weights of their onboarded vehicles, we are going to implement __add__() technique. Absolutely, that is overkill however complicating easy issues is a good way to be taught the fundamentals!

>> Whole weight of mustang and prius: 6542

🛑 Discover, how the core syntax work solely throughout the confines of the identical object kind — that means you possibly can run 'a' + 'b' and get a outcome however calling 'a' + 5 will end in an error. They function equally however has a built-in verify to make sure the operations are referred to as with the identical knowledge varieties. Verify the code block under:

attempt: 'a' + 5besides Exception as e:    print(e)attempt: mustang + 10besides Exception as e:    print(e)>> can solely concatenate str (not "int") to str
>> 'int' object has no attribute 'weight'

Additionally, discover the error variations thrown by our customized class situations vs an string object whereas operating the identical technique. This tells us that whereas implementing such particular strategies, we must also implement a verify to make sure the handed on object’s knowledge kind is of the anticipated kind or else elevate an exception.

We now have already seen the right way to look into the applied strategies from a category through the use of dir() perform. We are able to additionally use assist() perform to see the implementation of the strategies supplied that documentation is obtainable for that class. For instance, to take a look at the built-in technique of a string object we will run this: assist('a'.__class__).

Working this command will print out all of the strategies and take a variety of area so I’ve added a screenshot with solely a few strategies.

Picture supply: writer

On this article, we took a peek contained in the world of python’s core syntax. We talked about a few widespread core syntax and mentioned about their corresponding magic strategies. However there are much more magic strategies which might be already applied in Python. Checkout special methods reference page from Python.org for an in depth record of particular strategies

More Posts