Adventures in Machine Learning

Exploring the Exciting Features of Python 38: From Walrus Operator to Simplified Debugging

to Python 3.8

Python is one of the most popular programming languages in the world, and with every new release, it becomes even more powerful. The latest version, Python 3.8, was released in October 2019 and comes with exciting new features that make it even more user-friendly and efficient.

In this article, we’ll give you an overview of the new features that come with Python 3.8, so you can start exploring them today.

Overview of new features

Python 3.8 features several improvements and new functionalities that make coding in Python even easier and more efficient. These include:

1.

The Walrus Operator

One of the most awaited features of Python 3.8 is the walrus operator. This new operator, :=, allows you to assign values to variables within expressions.

It is called the “walrus” operator because the symbol resembles the eyes and tusks of a walrus. The walrus operator is particularly useful when working with while loops as it enables you to assign and test values at the same time.

Example:

Instead of writing:

age = int(input(“Enter your age: “))

while age < 18:

print(“You are too young.”)

age = int(input(“Enter your age: “))

You can use the walrus operator and write:

while age:= int(input(“Enter your age: “)) < 18:

print(“You are too young.”)

This code assigns age the value entered by the user and then checks if it’s less than 18. If it is, it prints the message “You are too young.”

2.

f-strings can now use “=” to specify a default value

f-strings, introduced in Python 3.6, enable you to embed expressions in string literals. In Python 3.8, f-strings can now use an equal sign to specify a default value for the expression.

If the expression returns None, the default value is used. Example:

# Without a default value

name = “Sarah”

print(f”Hello, {name.capitalize()}!”) # Output: Hello, Sarah!

# With a default value

age = None

print(f”You are {age=} years old.”) # Output: You are age=None years old.

3. Positional arguments can now have a forward slash

In Python 3.8, you can use a forward slash to separate positional arguments from keyword arguments in a function call.

This enables you to specify that all preceding arguments are positional, and all subsequent arguments are keyword arguments. Example:

# Without a forward slash

def add_numbers(x, y, z=0):

return x + y + z

print(add_numbers(1, 2, z=3)) # Output: 6

# With a forward slash separating the positional arguments

def add_numbers2(x, y, /, z=0):

return x + y + z

print(add_numbers2(1, 2, 3)) # Output: 6

4.

Other improvements

Python 3.8 also includes several other improvements that make it more user-friendly and efficient. Some of these include:

– Improved debugging: The new simplified debugging of your code feature allows you to easily debug your Python code by providing an easy-to-read traceback.

– Reversed iteration order: The reversed() function now returns an iterator instead of a list, making it more memory-efficient. – Precise types: Python 3.8 comes with advanced typing features that enable you to specify variable types using the typing module.

Conclusion

Python 3.8 is an exciting release that comes with several new features and improvements. While there are several new features, the Walrus operator, f-strings, and positional arguments with forward slash are particularly useful.

We hope this article has provided you with a useful overview of the new features that come with Python 3.8, so you can start exploring them today.

Positional-Only Arguments

Positional-only arguments are a new feature introduced in Python 3.8 that allow you to specify arguments that can only be passed by position and not by keyword. The syntax for specifying positional-only arguments is by using a forward slash (/) before the first named argument in the function definition.

Here is an example of a function that uses positional-only arguments:

“`

def my_function(a, b, /, c, d):

pass

“`

In this function definition, `a` and `b` are positional-only arguments, while `c` and `d` can be passed either by position or by keyword. When you call this function, you must pass `a` and `b` by position, like this:

“`

my_function(1, 2, 3, 4)

“`

You cannot pass `a` and `b` by keyword, like this:

“`

my_function(a=1, b=2, c=3, d=4)

“`

By using positional-only arguments, you can make your APIs more concise and easier to use, as some functions only allow for positional arguments to be set.

Positional-only arguments have been added to a few built-in functions, such as `divmod`, `pow`, and `sorted`. These functions now have one or more positional-only arguments, allowing them to be called more efficiently with less syntax.

More Precise Types

Python 3.8 introduces several new typing features that facilitate the use of type hints and annotations. These features aim to increase the precision and readability of types in Python code.

The new features cover literals, final objects, typed dictionaries, and protocols.

Literal types

A literal type is a type that can only take a specific value or a prescribed set of values. Python 3.8 introduces a new syntax for defining literal types by using a union with `Literal` class imported from the `typing` module.

Literal types enable us to define functions that take input arguments or return output values of specific values. Here is an example of a function that returns a literal value:

“`

from typing import Literal

def get_first_letter(word: str) -> Literal[‘A’, ‘B’, ‘C’]:

return word[0].upper()

“`

In this function, the return type annotation is defined using the `Literal` class. The function will only return one of the specified values ‘A’, ‘B’, or ‘C’.

Final Objects

Python 3.8 provides the final qualifier and @final decorator to implement immutability in Python. This feature is especially useful when we want to define constants that cannot be changed.

Final objects are denoted using the `final` keyword, which can be used as a type hint and can be specified before the variable name. Here is an example of final objects:

“`

from typing import final

MY_CONST: final[int] = 42

“`

In this example, the `final` keyword is used to specify that the variable `MY_CONST` cannot be assigned a new value after its definition.

Typed Dictionaries

Typed dictionaries are another new feature of Python 3.8. A typed dictionary is a dictionary type annotation that indicates the type of its keys and values. Typed dictionaries can be defined using the `TypedDict` class imported from the `typing` module.

Here is an example of a typed dictionary:

“`

from typing import TypedDict

class Person(TypedDict):

name: str

age: int

city: str

“`

In this example, `Person` is a typed dictionary with keys `name`, `age`, and `city`. The keys are given specific types to allow for proper annotation in code.

Protocols

Protocols are a new typing feature added in Python 3.8 that enable duck typing while providing some static type checking.

Protocols define a set of methods or attributes which a class may implement to fulfill a certain role.

Here is an example of a protocol:

“`

from typing import Protocol

class HasArea(Protocol):

def area(self) -> float:

pass

“`

In this example, `HasArea` is a protocol that defines the method `area()` which should be implemented by any class that intends to implement this protocol.

Protocols can be used in type annotations to provide a more precise and concise type for a class or function.

Conclusion

Python 3.8 introduces several new features that aim to increase the precision and readability of code. The addition of positional-only arguments, more precise typing features, and protocols facilitate the implementation of more concise and efficient code while providing strict type checking.

These additions make Python 3.8 a powerful tool for developers working with complex codebases or software architectures.

Simpler Debugging With f-Strings

Python 3.6 introduced formatted string literals, also known as f-strings. F-strings are a powerful tool for formatting strings in a concise and readable way.

F-strings allow you to include expressions within curly braces, much like the format() method. However, f-strings offer several benefits over format() method, including more concise syntax, greater readability, and efficient evaluation.

One of the most useful applications of f-strings is facilitating debugging. By using f-strings, you can easily add debugging information to your code without having to concatenate or format strings.

Here is an example of f-strings for debugging:

“`

def my_function(a, b):

print(f”Entering {__name__} with a={a}, b={b}”)

result = a + b

print(f”Exiting {__name__} with result={result}”)

return result

“`

In this example, the f-strings are used to print out the current status of the operation by passing in the values of `a` and `b`. F-strings provide debugging information directly within the string, making it easy to see the values of variables at any given point in the program.

This can save time when debugging, as developers can quickly identify the location of any errors and resolve them efficiently.

The Python Steering Council

The Python Steering Council is a new governance model for Python development that was introduced in 2019. The Steering Council replaces the previous governance model, the Python Software Foundation (PSF), and provides a more structured and transparent approach to how Python is developed.

The Steering Council is responsible for managing the development of Python, making decisions on major changes, and guiding the direction of future development. The Council is made up of five core members, in addition to the Python release manager and a representative from the PSF.

The Python Steering Council is designed to bring greater clarity and accountability to the development process, ensuring that Python remains an open-source project that is guided by the needs of the community. The Council works closely with Python’s large and diverse community of developers and users to ensure that Python remains a powerful tool for developers working on everything from small projects to large-scale enterprise systems.

One of the most significant changes the Steering Council has implemented is a more structured and transparent approach to decision-making. Decisions are made through a consensus-based process, with input solicited from the community and stakeholders at all stages of development.

This approach ensures that the needs of all stakeholders are taken into account, and that decisions are made in the best interests of the Python community as a whole.

Conclusion

Python 3.8 introduces several new features, including f-strings, final objects, positional-only arguments, and typed dictionaries, which make it even more powerful and user-friendly. By using these features, developers can write concise and efficient code while ensuring that the code is reliable and easy to read.

Additionally, the introduction of the Python Steering Council provides a more transparent and accountable approach to the development of the language, ensuring that Python remains an open-source project that continues to evolve and serve the needs of its community.

Other Pretty Cool Features

Python 3.8 also includes several small improvements and optimizations that enhance its performance and usability. Some of the additional features include:

1.

Improved performance with vectorcall

Python 3.8 introduces a new protocol called vectorcall. This protocol improves the performance of function calls by optimizing the calling conventions.

The vectorcall feature is especially useful for functions that have multiple arguments. 2.

Reducing memory usage with shared memory

Python 3.8 introduces the SharedMemory class, which allows multiple processes to access the same memory. This feature reduces the amount of memory that is used when multiple processes are running.

3. Simplified module initialization

Python 3.8 introduces a new C-API function called PyModuleDef_Init.

This function simplifies module initialization, making it easier for developers to define modules and reduce code duplication. 4.

Improved debugging for threading

Python 3.8 introduces a new flag called `DEV_MODE` that enables developers to test their code for potential threading issues. This feature helps catch potential problems before they can cause issues for users.

5. Delayed evaluation of type annotations

Python 3.8 also allows for delayed evaluation of type annotations until runtime.

This feature enables Python to work more efficiently with forward references and other complex type hierarchies. These small improvements and optimizations make Python 3.8 a more efficient and user-friendly programming language that can handle more complex and demanding tasks.

Should You Upgrade to Python 3.8?

Upgrading to Python 3.8 depends on several factors, including your programming needs and the compatibility of your existing code. While Python 3.8 comes with several new features and improved performance, it is not always necessary to upgrade immediately.

Here are some considerations and advice for upgrading to Python 3.8:

1. Check if your existing code will work with Python 3.8

Before upgrading, it’s essential to check if your existing code will be compatible with Python 3.8. Libraries and code that work with earlier versions of Python may need to be updated or replaced to work with 3.8.

2.

Understand the new features and functionality

Python 3.8 comes with several new features and optimizations, some of which may be beneficial for your development needs. Ensure that you understand the new features and functionality and how they can help you with your projects.

3. Consider the impact on third-party libraries

Third-party libraries that you rely on may not be updated to work with Python 3.8 immediately.

Consider the impact on your development workflow and critical systems if you have to wait for updates from third-party libraries. 4.

Consult with others in your industry

Consult with colleagues or other developers in your industry to see if they have already upgraded to Python 3.8. This can help you understand the benefits and challenges of the upgrade and provide insights on how to make the transition easier. 5.

Consider other versions of Python

Python 3.8 is not the only version of Python available, and other versions may be better suited for your specific needs. Python 3.7 and 3.9 also come with new features and optimizations while maintaining backward compatibility with older versions of Python.

In conclusion, upgrading to Python 3.8 can bring several benefits to your development workflow, including improved performance and usability. However, before making the transition, it’s essential to consider the impact on your existing code, third-party libraries, and development processes.

Upgrading to Python 3.8 may not be necessary or feasible for everyone, and careful consideration and planning should be given to determine the best course of action. Python 3.8 is a powerful programming language for developers looking to improve the efficiency and readability of their code.

With the introduction of features such as f-strings, literal types, and positional-only arguments, Python 3.8 provides developers with a more concise, efficient, and user-friendly development environment that can handle complex tasks. Additionally, the new governance model provided by the Python Steering Council ensures that Python remains open-source and community-centered.

While upgrading to Python 3.8 presents several benefits, developers must take into consideration compatibility issues and the impact on existing code before making the transition. In summary, Python 3.8 provides developers with valuable new features and optimizations that can improve their workflow and help them build robust and efficient software for a wide range of applications.

Popular Posts