SoFunction
Updated on 2024-10-28

A look at five implicit features in Python

1. Introduction

Recently, in my spare time, I will go to read some Python documentation, and sometimes I will notice some interesting Python features that can't help but make people exclaim: "Wow, Python can be written this way".

Without further ado, let's get right to it. :)

2. Functional attributes

Similar to setting properties for classes and objects, we can set properties for functions in Python. The sample code is as follows:

def func(x):
    intermediate_var = x**2 + x + 1
    if intermediate_var % 2:
        y = intermediate_var ** 3
    else:
        y = intermediate_var **3 + 1
    # setting attributes here
    func.optional_return = intermediate_var
    func.is_awesome = 'Yes, my function is awesome.'
    return y
y = func(3)
print('Final answer is', y)
# Accessing function attributes
print('Show calculations -->', func.optional_return)
print('Is my function awesome? -->', func.is_awesome)

Looking at the above code, we have set the function attribute 'optional_return' at line 9 and 'is_awesome' at line 10. Also, in the last two lines of the call statement we have accessed the values of these two function attributes.

The above code runs as follows:

Final answer is 2197
Show calculations --> 13
Is my function awesome? --> Yes, my function is awesome.

The writing of the function attributes above will come in handy when we want to optionally check for intermediate variables in some functions, but don't want to explicitly return it with a return statement each time the function is called.

3. For-else loops

In Python, you can add an else statement to a for loop. The else statement is triggered only if no break statement is encountered in the loop body during execution. Here's a sample code:

my_list = ['some', 'list', 'containing', 'five', 'elements']
min_len = 3
for element in my_list:
    if len(element) < min_len:
        print(f'Caught an element shorter than {min_len} letters')
        break
else:
    print(f'All elements at least {min_len} letters long'

The output of the above code is as follows:

All elements at least 3 letters long

Looking at the above code, else is indented at the for level instead of the if level. Here, no element is less than 3. Therefore, a break statement will never be encountered. Therefore, the else clause will be triggered (after the execution of the for loop) and print the output shown above.

4. int separator

In general, it is visually difficult for the human eye to distinguish between the numbers 10,000,000 and 10,000,000, and in Python we can't just use comma separators to separate the numbers like we can in English, because Python interprets comma-separated numbers as tuples of integers.

However, Python has a convenient way to handle this situation: we can use an underscore as a separator to improve the readability of numbers, where the number 1_000_000 will be interpreted as a shaped number and increase readability.

Sample code is shown below:

a = 3250
b = 67_543_423_778
print(type(a))
print(type(b))
print(type(a)==type(b))

The results of the run are as follows:

<class 'int'>
<class 'int'>
True

5. eval() and exec()

Python has the ability to dynamically read a string and treat it as a piece of Python code. This is accomplished primarily through the use of the eval() and exec() functions ("eval" for evaluating expressions and "exec" for executing statements).

An example of the code is shown below:

a = 3
b = eval('a + 2')
print('b =', b)
exec('c = a ** 2')
print('c is', c)

The results of the run are as follows:

b = 5
c is 9

In the above code, eval() function reads the input string as a Python expression, evaluates it and assigns the result to the variable "b". Meanwhile, exec() function reads the input string as a Python statement and executes it.

6. Ellipsis

The ellipsis or "..." is a built-in constant in Python, similar to built-in constants like None, True, False, and so on. It can be used in different ways, including but not limited to:

6.1 Placeholders

Similar to pass, the ellipsis can be used as a placeholder when the code is not complete, as in the following example:

def some_function():
    ...
def another_function():
    pass

6.2 numpy arrays used in slicing

Arrays can be sliced in NumPy using ellipses. The following code shows two equivalent methods for slicing NumPy arrays:

import numpy as np
a = (16).reshape(2,2,2,2)
print(a[..., 0].flatten())
print(a[:, :, :, 0].flatten())

The results are as follows:

[ 0  2  4  6  8 10 12 14]
[ 0  2  4  6  8 10 12 14]

7. Summary

Python is not only a useful language, but also a very interesting one. We are all busy with our lives and work, but it doesn't hurt to know some features of the language itself for better understanding. In this article, 5 implicit features in Python are highlighted and an explanation of the relevant code is given.

That's all for this post, I hope it was helpful and I hope you'll check back for more from me!