Python
- Tags
- language
A modern readable and user friendly dynamically and strongly typed interpreted programming language.
Note: Newer versions of cpython compile python code into python bytecode implicitly whenever you try to run a python script. The interpreter then interprets this bytecode. This means one could classify python as a p-code language.
Pythonic
A term used to describe python code follows certain stylistic and conventional guidelines.
Being Pythonic means clarity, efficiency, and credibility.
CPython
The reference python implementation, written in C.
Language
Context Managers
Are pythons mechanism for automatic resource management.
The simplest example of this you're likely to have encountered is the open
method.
with open('foo.txt', 'r') as fd:
pass
Within the body of this with
block the file foo.txt
has been opened and assigned
to the variable fd
. No matter what happens in the body, outside of the body the
file will be closed and any resources for it freed. This is the case if an
exception has been thrown or not.
There are 2 ways to write a context manager. Using the contextmanager
decorator or
a class with the necessary fields of a context manager.
Class Based
class Messenger:
def __init__(self, message):
self._message = message
def print(self):
print(self._message)
def __enter__(self):
# The enter method is run whenever the with block is
# entered. The value returned from here can be assigned
# in the with block using the ~as variable~ syntax.
return self
def __exit__(self, exc_type, exc_value, exc_tb):
# The exit method is run to clean up any resources before
# the with block is exited. Notice if an exception was
# thrown the exit block can inspect it.
#
# To handle the exception within the with block, this method
# can return True.
pass
with Messenger("secret message") as msg:
msg.print() # secret message
Decorator Based
import contextlib
@contextlib.contextmanager
def messenger(msg):
# Place any setup or initialisation logic here.
yield msg
# Place any cleanup or exit logic here.
with Messenger("secret message") as msg:
print(msg) # secret message
Note: You can also handle exceptions with the decorator approach by wrapping the
yield
call in a try/catch expression.