DEV Community

Cover image for Introduction to modern python
Marriane Akeyo
Marriane Akeyo

Posted on

Introduction to modern python

Python is an interpreted, high-level language created by Guido van Rossum and released in 1991. It is dynamically typed and garbage collected.Python programs have the extension.py and can be run from the command line by typing python file_name.py.The common features provided by python include:
-Simplicity: This includes less of the syntax of the language and more of the code.
-Open Source: A powerful language and it is free for everyone to use and alter as needed.
-Portability: Python code can be shared and it would work the same way it was intended to.
-Embeddable & Extensible: Python can have snippets of other languages inside it to perform certain functions.
-Being Interpreted: The worries of large memory tasks and other heavy CPU tasks are taken care of by Python itself leaving you to worry only about coding.
-Huge amount of libraries:from data science all the way to web development.
-Object Orientation: Objects help breaking-down complex real-life problems into such that they can be coded and solved to obtain solutions.
A simple hello world in python can be written as:

print("Hello world")
Enter fullscreen mode Exit fullscreen mode

What therefore do we mean when we say modern python?How is it helpful in a programmers life and why should we prefer it to the old python language?
Modern python simply means agreed modern best practices that are used when coding in python in order to give you better results .They include:

Tooling

1.Use of python3
Python3 is the latest existing version of python that is being supported by all the major libraries and frameworks.Hence advisable for use.
2.Use of virtual environment
It enables you to define separate sets of packages for each Python project, so that they do not conflict with each other.
There are several tools that help you to manage your Python projects, and use virtual environments. The most popular are pipenv and poetry. Poetry is considered to be better designed, but pipenv is more widely supported. If you prefer, you can also manually set up and manage virtual environments.
3.Formatting your code
Use a formatting tool with a plugin to your editor, so that your code is automatically formatted to a consistent style.
Black is being adopted by the Python Software Foundation and other projects. It formats Python code to a style that follows the PEP 8 standard, but allows longer line lengths. Use Black for new projects.

Language Syntax

1.Format strings with f string

The new f-string syntax is both more readable and has better performance than older methods.A good example of the fstring includes:

name = "nduta"
print(f'Hi, my name is {name}')
Enter fullscreen mode Exit fullscreen mode

You can use either the double or single quotes.
2.Use enum or Named Tuples for Immutable Sets of Key-Value Pairs.
The properties of an enumeration and named tuples are useful for defining an immutable, related set of constant values that may or may not have a semantic meaning.
3.Create Data Classes for Custom Data Objects
The data classes feature enables you to reduce the amount of code that you need to define classes for objects that exist to store values.
4 Use collections.abc for Custom Collection Types
They provide the components for building your own custom collection types.These classes are well dvocated for because they are fast and well-tested.
5.Use breakpoint() for Debugging
This function drops you into the debugger,both the inbuilt and external debuggers can use these breakpoints.An example would be:

foo()
breakpoint()
bar()
Enter fullscreen mode Exit fullscreen mode

The above code simply states that python will enter into the debugger after executing foo() and before executing bar().

Application design

1.Use Logging for Diagnostic Messages, Rather Than print()

The built-in print() statement is convenient for adding debugging information, but you should include logging in your scripts and applications. Use the logging module in the standard library, or a third-party logging module.

2.Only Use asyncio Where It Makes Sense

The asynchronous features of Python enable a single process to avoid blocking on I/O operations. You can achieve concurrency by running multiple Python processes, with or without asynchronous I/O.

To run multiple Web application processes, use Gunicorn or another WSGI server. Use the multiprocessing package in the Python standard library to build custom applications that run as multiple processes.

Code that needs asynchronous I/O must not call any function in the standard library that synchronous I/O, such as open(), or the logging module.

If you would like to work with asyncio, always use the most recent version of Python. Each new version of Python has improved the performance and features of async.

Libraries

1.Handle Command-line Input with argparse

The argparse module is now the recommended way to process command-line input. Use argparse, rather than the older optparse and getopt.
The optparse module is officially deprecated, so update code that uses optparse to use argparse instead.

2.Use pathlib for File and Directory Paths

Use pathlib objects instead of strings whenever you need to work with file and directory pathnames.

Consider using the the pathlib equivalents for os functions.

The existing methods in the standard library have been updated to support Path objects.

To list all of the the files in a directory, use either the .iterdir() function of a Path object, or the os.scandir() function.
3.Use os.scandir() Instead of os.listdir()

The os.scandir() function is significantly faster and more efficient than os.listdir(). Use os.scandir() wherever you previously used the os.listdir() function.

This function provides an iterator, and works with a context manager:

import os

with os.scandir('some_directory/') as entries:
    for entry in entries:
        print(entry.name)
Enter fullscreen mode Exit fullscreen mode

The context manager frees resources as soon as the function completes. Use this option if you are concerned about performance or concurrency.

The os.walk() function now calls os.scandir(), so it automatically has the same improved performance as this function.
4.Run External Commands with subprocess
The subprocess module provides a safe way to run external commands. Use subprocess rather than shell backquoting or the functions in os, such as spawn, popen2 and popen3. The subprocess.run() function in current versions of Python is sufficient for most cases.
5.Use Requests for HTTP Clients
Use the requests package for HTTP, rather than the urllib.request in the standard library.
6.Test with pytest
The pytest package has super-ceded nose as the most popular testing system for Python hence most advisable .You can use unittest for situations where you cannot add the pytest library to your project.
This is just a sample of the modern improvements done in python . As they always say , practice makes perfect.So working with the language and its packages will give you a clear picture of the dos and don't s.If you haven't started using the library ,my advise would be to give it a shot and see how far it goes.The language also has a wide community which is willing to help once you get stuck.
Those who are advanced in the same my take would be to be on the look out since change is inevitable especially in the tech industry.
I hope this gives you some incite.

Top comments (0)