Python Programming: How Much Do You Know About Core Protocols: Function Protocol Numbers and Context Management Protocols

Python Programming: How Much Do You Know About Core Protocols: Function Protocol Numbers and Context Management Protocols

Preface

In the previous few articles, several core components of Python, including object protocol, number protocol, comparison protocol, conversion protocol, container protocol, iteration protocol, and attribute protocol, were briefly introduced with example codes.

This article introduces the Function Protocol and the Context Manager Protocol.

Function Protocol

We know that Python is a dynamic language. The interpreter reads the code and interprets it. This involves the interpretation and execution of functions (in the context of a class, the functions of the object to which they belong are called methods), so certain protocol rules must be followed, otherwise it will be a mess.

In an object, an object can simulate a function by providing a __call__() method. Assuming an object x provides this method, it can be called like a function. In other words, x(__arg1, arg2, ...) actually calls x.__call__ (__arg1, arg2, ...). A simple example is as follows:

 class XxxCalling :

def __call__ ( self , name , where ) :

s = f "My name is {name} and I'm from {where}."

print ( s )



xc = XxxCalling ( )

xc ( 'Zulong' , 'China' )

In fact, the last line of the above code can also be written as: xc.__call__('祖龙', '中国'), the result is exactly the same. For callable objects, in fact, "name()" can be understood as an abbreviation of "name.__call__()".

Many built-in types support function calls. For example, types implement __call__() to create new instances. Bound methods implement __call__() to pass the self argument to instance methods. Library functions like functools.partial() also create objects that emulate functions.

Context Management Protocol

The so-called context management protocol here mainly refers to a block of code in a specific scope. Python uses the with statement to implement it, that is, the with statement allows a series of statements to be executed under the control of an instance called a context manager. The general syntax is as follows:

 with context [ as var ] :

statements

Implementing such a context protocol requires supporting the following specific methods:

  • __enter__(self) method: This function is called at the point of entry into a new context. The return value is placed in the variable specified by as listed with the with statement.
  • __exit__(self, type, value, tb) method: called when leaving the context. If an exception occurs, type, value, and tb contain the exception type, value, and related tracking information.

The __enter__() method is called when a with statement is executed. The value returned by this method is placed into the variable specified with the optional as var specifier. The __exit__() method is called when control-flow leaves the block of statements associated with the with statement. As arguments, __exit__() receives the current exception type, value, and, if an exception was raised, a traceback. If no error was handled, all three values ​​are set to None. The __exit__() method should return True or False to indicate whether the raised exception was handled. If it returns True, any pending exception is cleared and program execution continues normally with the first statement after the with block.

The primary purpose of the context management interface is to allow simplified resource control over objects that involve system state, such as open files, network connections, and locks. By implementing this interface, an object can safely clean up resources when execution leaves the context in which it is used.

summary

This is all I have to say for this article. I have briefly introduced the implementation of the function protocol (directly calling objects as functions) and the implementation of the context protocol.

<<:  Five ways 5G will change manufacturing

>>:  How will 6G change the workplace?

Recommend

Why do base stations need to go to the sky?

Over the past few decades, mobile communication t...

Why does 6G run so fast?

The latest 6G speed created by Chinese scientists...

How cloud services enable a 5G-driven future

As high-speed cellular networks become mainstream...

Detailed explanation of the differences between IPv6 and IPv4!

IPv6 is the abbreviation of Internet Protocol Ver...

Enterprise IoT threatens to undermine cloud and IT security

We had so much trouble getting security back to n...

Ericsson and Swisscom sign standalone 5G network agreement

Ericsson and Swisscom have signed an expanded 5G ...

How to Choose and Buy Network Automation Tools

The concept of network automation has been around...

...

5G and cybersecurity risks in 2023

The rollout of 5G networks has been alarmingly sl...

OlinkCloud: $5.6/month KVM-1GB/10G SSD/500GB/San Jose

Tribe shared the news about Olink.Cloud in Novemb...