9 Python 3 Features You Might Not Use Yet



Several developers have started to shift their Python version from 2 to 3 due to Python EOL. One of the most well-known changes is that the print() function in Python 3 replaces the print function in Python 2. However, parentheses work in Python 2 if a space is added after the print keyword because the interpreter evaluates it as an expression.

Here are a few illustrations of uncommon traits that can only be found in Python 3, with the intention of fixing your Python issues quickly.

All examples are coded in Python 3.8.0.


1. Enumerations

Python 3 allows you to write enumerations in Enum class in an easy way. Enumerations are formed with the class syntax, which facilitates reading and writing them easily, but without any structure — they don’t arise readily by code.


from enum import Enum, auto
class Fruit(Enum):
APPLE=auto()
ORANGE=auto()
GUAVA=auto()
print(Fruit.APPLE)

# Fruit.APPLE

An enumeration is a collection of symbolic terms (members) associated with particular, fixed values. In an enumeration, the symbolic names could be differentiated via naming as well as iterating the enumeration alone.


for fruit in Fruit:
 print(fruit)
 
-> Fruit.APPLE
-> Fruit.ORANGE
-> Fruit.GUAVA



2. Type Hinting

Static, as against dynamic, typing is a hot subject in computer languages, and everybody has a perspective on it. I’ll allow the viewer to think when to write types. However, I feel you must learn that type hints is supported by Python 3.

def fruits_word(line: str) -> bool:
  return "fruit" in linetest = fruits_word("I love to eat fresh fruits")
print(test)
# True



3. Pathlib

F-strings are incredible, but strings such as file paths have their own libraries that make it easier to manipulate them. The Pathlib module simplifies a variety of complex cases, and it also optimizes some of the simple cases. As a convenient abstraction for working with file paths, Python 3 provides pathlib.


from pathlib import Path 
root=Path('blog_new_folder')
print(root)
# blog_new_folder
path=root/'new_program'print(path.resolve())
# /home/vivekcoder/Workspace/My_Programming/Medium-Articles/python3_uncommon_features/blog_new_folder/new_program

I feel this post will inspire you to use the Python Pathlib module whenever you need to deal with Python files.


4. F-Strings

It is hard to perform anything in whatever programming language without strings, and you expect a structured way to work with strings to stay productive. Most people who use Python prefer to use the format method.


import datetime 
name="Vivek" 
activity="writing Medium article"
time=datetime.date(2020, 8, 15)

message='My name is {}, I completed an activity {} on {}.'.format(name, activity, time)

print(message)
# My name is Vivek, I completed an activity writing Medium articleon
2020-08-15.

In addition to the format, Python 3 provides a versatile way of interpolating strings via f-strings. The above code with f-strings appears as below:


import datetime
name="Vivek"
activity="writing Medium article"
time=datetime.date(2020, 8, 15)

message=f'My name is {name}, I completed an activity {activity} on {time:%A, %B %d, %Y}.'
print(message)
# My name is Vivek, I completed an activity writing Medium article on
Saturday, August15, 2020.

F-strings create even more understandable and usable code than utilizing string concatenation or format strings.

F-strings allow expressions to be integrated into string literals by a minimal syntax. It should be observed that an f-string is really a runtime expression, not a fixed value.



5. Built-In LRU Cache

An LRU (least recently used) cache performs very well if the newest calls are the best predictors for incoming calls. (The most common news server posts, for example, vary every day). The size restriction of the cache means that the cache does not expand without long-running cycles like web servers.

When the user function is defined, it must be a callable. This makes it possible in Python 3 to apply the lru_cache decorator directly to a user function.

Below is an example of a Fibonacci function that we understand will benefit from caching because, with a recursion, it does the same job several times.


import time 
def fibon(number: int) ->int:
    if number==0: return0
    if number==1: return1
    return fibon(number-1) +fibon(number-2)
start=time.time()
fibon(20)
print(f'Duration: {time.time() -start}s')
->Duration: 0.007005214691162109s

Here we can utilize lru-cache to configure it. (This optimization method is termed memoization). The decorator covers a function with a memoizing callable that stores the maxsize of the most recent calls.

from func tools import lru_cache
@lru_cache(maxsize=512) 
def fib_memoization(number: int) ->int:
    if number==0: return0
    if number==1: return1

    return fib_memoization(number-1) +fib_memoization(number-2)
start=time.time()
fib_memoization(20)
print(f'Duration: {time.time() -start}s')
->Duration: 4.341516078231e-09s


6. Extended Iterable Unpacking

I’m going to allow the code to respond below. An example depicts the feature better than 1,000 words:


x, *y, z=range(4)
print(x, y, z)
# 0 [1, 2] 3
python_version, file_name, topic, *output="python3.0 hello.py betterprogramming 1 2 3 4".split()
print(python_version)
print(file_name)
print(topic)
print(output)
# python3.0# hello.py
# better programming
# ['1', '2', '3', '4']
a, b, c, *d=range(7)
print(b, d)
# 1 [3, 4, 5, 6]

Refer to the official Python 3 documentation here for further clarity on extended iterable unpacking.


7. Underscores in Numeric Literals

Python 3.6 offers an exciting approach to help reading numerical literals by enabling the numbers to be underscored. It can be applied to describe, for instance, thousands, hexadecimal, and binary numbers.


price=50_000
print(f'Price: {price}')
# Price: 50000
hexa_val=0xABCD_EFD9
print(f'Decimal equivalent: {hexa_val}')
# Decimal equivalent: 2882400217
bin_ary=0b_0010_0110
print(f'Decimal: {bin_ary}')
# Decimal: 38


8. Assignment Expressions — ‘walrus’ Operator

With Python’s latest release, the walrus operator is introduced, which makes a variable assignment of expression. It can be helpful if you intend to refer to the appearance later in code, and it can save a line or two of code.

birds = [‘owl’, ‘hen’, ‘duck’, ‘parrot’]

for bird in birds:
    if (len_bird := len(bird)) > 4:
        print(f’A bird “{bird}” consists of{len_bird}, letters’)

# A bird “parrot” consists of6, letters

9. Data Classes

Python 3 provides data classes, which have few restrictions and can be used to minimize boilerplate code since the decorator automatically generates unique methods like __init__( ) and __repr__( ). The official proposal lists them as “mutable named tuples with defaults.”

class Item_list:
    def__init__(self, name: str, perunit_cost: float, 
    quantity_available: int=0):
        self.name=name
        self.perunit_cost=perunit_cost
        self.quantity_available=quantity_available
        
    def total_cost(self) ->float:
        return self.perunit_cost * self.quantity_available
        
book=Item_list("better programming.", 50, 2)
x=book.total_cost()
print(x)
# 100print(book)# <__main__.Item_list object at 0x00000052DB9D2A48>

Using the @dataclass decorator, you can write the same implementation:

from dataclasses import dataclass
@dataclass 
class Item_list:
      name: str
      perunit_cost: float
      quantity_available: int=0
      def total_cost(self) ->float:
            return self.perunit_cost * self. quantity_available

book=Item_list("better programming.", 50, 2)
x=book.total_cost()
print(x)# 100print(book)
# Item_list(name='better programming.', perunit_cost=50, quantity_available=2)

Refer to the official Python 3 documentation for further clarity on dataclass.


The Key Takeaway

There are no magic recipes — it’s all about discipline, smart work, a lot of patience, and practice. Every day, you need to learn new things and enjoy working because this is the only way you will grow. I believe that the above insight shows you at least one of the Python 3 additional features not previously recognized and encourages you to start writing cleaner and far more intuitive code.


Source: Medium.com

Recent Posts

See All

Tuning using HyperOpt in python

HyperOpt provides an optimization interface that accepts an evaluation function and parameter space, and can calculate the loss function value of a point in the parameter space. The user also specifie