Summary of five implicit features in Python

Posted by jabba_29 on Thu, 27 Jan 2022 01:16:37 +0100

1. Introduction

In my spare time recently, I will read some Python documents and sometimes notice some interesting Python features. These features can't help exclaiming: "Wow, python can still write like this.".

Don't gossip, let's start directly

2. Function properties

Similar to setting the properties of classes and objects, we can also 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)

Observing the above code, we set the function attribute 'optional' on line 9_ Return 'set the attribute' is' on line 10_ awesome’. At the same time, in the last two lines of the call statement, we access the values of the two function attributes.
The running results of the above code are as follows:

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

When we want to check the intermediate variables in some functions, but don't want to use the return statement to return it explicitly every time we call the function, the above function properties will come in handy.

3. For else cycle

In Python, we can add else statements to the for loop. The else statement is triggered only if no break statement is encountered in the loop body during execution. The sample code is as follows:

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 above code output is as follows:

All elements at least 3 letters long

Looking at the code above, else is indented at the for level, not at the if level. Here, no element has a length less than 3. Therefore, you will never encounter a break statement. Therefore, the else clause will be triggered (after executing the for loop) and print the output shown above.

4. int separator

Generally speaking, from the visual effect, it is difficult for the human eye to distinguish the numbers 10000000 and 100000000. In Python, we can't directly use the comma separator to separate the numbers as in English, because Python will interpret the numbers separated by commas as as the tuples of multiple integers.

However, Python also has a convenient way to deal with this situation: we can use underscores as separators to improve the readability of numbers. At this time, the number 1_ 000_ 000 will be interpreted as an integer number and increased readability. The code example is as follows:

a = 3250
b = 67_543_423_778

print(type(a))
print(type(b))
print(type(a)==type(b))

The operation results are as follows:

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

5. eval() and exec()

Python has the ability to dynamically read strings and treat them as a piece of Python code. This is mainly achieved by using eval() and exec() functions ("eval" is used to evaluate expressions and "exec" is used to execute statements).

Code examples are as follows:

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

The operation results are as follows:

b = 5
c is 9

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

6. Ellipsis

Ellipsis or "..." are Python's built-in constants, similar to built-in constants such as None, True, False, etc. It can be used in different ways, including but not limited to:

6.1 placeholder

Similar to pass, the ellipsis can be used as a placeholder when the code is not completely written, for example:

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

6.2 for slicing in numpy array

Using ellipsis in NumPy can slice arrays. The following code shows two equivalent methods for slicing NumPy arrays:

import numpy as np
a = np.arange(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 language. We are all busy with life, but there is no harm in order to better understand some characteristics of language itself. In this article, we focus on the five implicit features in Python and explain the relevant codes.

Have you failed in your studies?


Pay attention to the official account of AI algorithm and get more AI algorithm information.

reference resources

Topics: Python