In this post we’ll go through the different uses of the _
character in Python. Like with many things in Python, we’ll see that different usages of _
are mostly (not always!) a matter of convention. Here are the five different cases we’ll cover:
_
)_total
)total_
)100_000
)__total
)__init__
)This is typically used in 3 cases:
The _
name points to the result…
This post discusses Python’s NotImplemented
built-in constant/type; what it is, what it means and when it should be used.
>>> type(NotImplemented)
<type 'NotImplementedType'>
NotImplemented
is one of Python’s six constants living in the built-in namespace. The others are False
, True
, None
, Ellipsis
and __debug__
. Similar to Ellipsis
, NotImplemented
can be reassigned (shadowed). Assignments to it, even as an attribute name, do not raise a SyntaxError
. So it isn’t really a “real/true” constant. Of course, we should never ever re-assign it. But, for completeness:
>>> None = 'hello' ... SyntaxError: can't assign to keyword >>> NotImplemented NotImplemented >>> NotImplemented = 'do…
This post discusses Python’s from <module> import *
and from <package> import *
, how they behave and why it may be (is!) a bad idea to use them.
from <module> import *
means “I want access to all the names in <module>
that I’m meant to have access to”. So, let’s say we have the following something.py
:
# something.pypublic_variable = 42
_private_variable = 141def public_function():
print("I'm a public function! yay!")def _private_function():
print("Ain't nobody accessing me from another module...usually")class PublicClass(object):
passclass _WeirdClass(object):
pass
In the Python Interpreter, we can execute from something import *
and see…
This post discusses the else
clause in Python’s try
statement. Although this particular use of else
may not be as forgotten and controversial as its use in Python loops, a gentle reminder of how it works and when it’s useful may still be beneficial. Please note that this post only focuses on the else
clause of the try
statement and does not intend to cover the entire try
statement. For a pretty good initial explanation of how the entire try
statement works, refer to the official Python documentation on this topic.
A “normal” stripped down try
statement seen regularly looks…
In this post we’ll discuss Python’s for...else
and while...else
syntax, one of the most rarely used and misunderstood features in Python.
Both for
and while
loops in Python also take an optional else
suite (like the if
statement and the try
statement do), which executes if the loop iteration completes normally. In other words, the else
suite will be executed if we don’t exit the loop in any way other than its natural way. So, no break
statements, no return
statement, or no exceptions being raised inside the loop. Consider a simple (and useless) example:
In the code above…
Co-founder & CTO at Metaview. Previously, Palantir, Osper, and Morgan Stanley. I love a silly salmon with a good egg. @s16h_ on Twitter.