DEV Community

Arjun Vijay Prakash
Arjun Vijay Prakash

Posted on

🐍4️⃣ Advanced Python Concepts Every Programmer Needs 🔥⚡️

🌟 Introduction

In this article, discover efficient ways to manage contexts and enhance code documentation using DocStrings.

Create lists using expressions.

Explore the advanced tools that Python provides and dive into the __future__ module, which allows for time travelling(haha, I really wanted to use this phrase) between different versions of Python.


1️⃣ Context Managers

Context managers in Python are objects that have two methods, __enter__ and __exit__.

They are utilized with the statement to ensure the management of specific operations such as opening and closing files.

import time

class Timer:
    def __enter__(self):
        self.start_time = time.time()
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        elapsed_time = time.time() - self.start_time
        print(f"Elapsed time: {elapsed_time} seconds")

# Using the Timer context manager
with Timer():
    # Some time-consuming operation
    for _ in range(1000000):
        pass
Enter fullscreen mode Exit fullscreen mode

In this case, the Timer class acts as a context manager. The __enter__ & __exit__ methods define the start and end actions.

When the code block within the with statement is executed the elapsed time is automatically displayed.

Context managers prove to be useful, for managing resources and can be customized according to different requirements.


2️⃣ Function Annotations / DocStrings

In Python, you have the option to use function annotations or more commonly, DocStrings which are strings or comments specified in code that are used to document a function.

def add_numbers(a: int, b: int) -> int:
    """
    Adds two numbers and returns the result.
    """
    return a + b

result = add_numbers(3, 5)
print(result)  # Output: 8
Enter fullscreen mode Exit fullscreen mode

In this example, we have parameter annotations, for a and b which indicate the expected argument types.

The annotation -> int specifies that the function should return an integer.

While annotations are not mandatory and do not enforce type checking they can make code more readable and serve as documentation.


3️⃣ List Comprehensions with Conditional Expressions

Python offers list comprehensions as a method, for creating lists.

However, you can further enhance them by incorporating expressions.

This allows you to filter elements based on conditions while constructing the list.

Example:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Create a list of squares for even numbers only
squares_of_evens = [x**2 for x in numbers if x % 2 == 0]

print(squares_of_evens)  # [4, 16, 36, 64, 100]
Enter fullscreen mode Exit fullscreen mode

In this case, the list comprehension incorporates a condition (if x % 2 == 0) to guarantee that only even squared numbers are added to the resulting list.


4️⃣ __future__ Module

The __future__ module in Python allows you to activate Python features from some other version in your existing code.

This proves useful when transitioning code to a Python version while ensuring compatibility, with the current version.

Example:

from __future__ import division

result = 5 / 2
print(result)  # Output: 2.5
Enter fullscreen mode Exit fullscreen mode

In this example, we utilize the module to activate the division behaviour introduced in Python 3.

This behaviour ensures that when integers are divided the result is a float, then an integer as it would be in Python 2, without this import.


🙌 Wrapping Up

My challenge to you is to find a way to utilize some of these concepts.

When you use them a few times, they end up sticking in your mind and then you start to see tons of ways to use them in the future too.

And boom!

Congratulations! Now you have cool extra tools in your Python toolkit ready for use!

I hope you liked the article! ❤️

Connect with me: linktree

Happy Coding! 🚀
Thanks for 14081! 🤗

Top comments (4)

Collapse
 
sehgalspandan profile image
Spandan Sehgal

Hey,
I was not active on dev.to lately as I was experiencing that the genuine and valuable content creators are going away... but looking at some recent posts of yours, I think I was wrong.

Nice content and definitely helpful.... i learned so many things from this post.

Keep it up!

Collapse
 
arjuncodess profile image
Arjun Vijay Prakash

Thank you from the depths of my heart!

Your words mean the world to me and it feels good to connect after a while, Spandan!

Knowing I've helped you inspires me hugely.

Thanks for the comment, brother!

Collapse
 
toskumar profile image
Senthil Kumar G

Dear Author,

Good to learn some new concepts in Python.

Thanks
Senthil

Collapse
 
arjuncodess profile image
Arjun Vijay Prakash

I'm delighted to hear that! Thanks to you too!