{"id":119,"date":"2015-01-13T07:00:59","date_gmt":"2015-01-13T12:00:59","guid":{"rendered":"http:\/\/pfsensesetup.com\/pythonscript.net\/?p=119"},"modified":"2015-01-12T18:01:19","modified_gmt":"2015-01-12T23:01:19","slug":"python-exceptions-part-six","status":"publish","type":"post","link":"http:\/\/pfsensesetup.com\/pythonscript.net\/python-exceptions-part-six\/","title":{"rendered":"Python Exceptions: Part Six"},"content":{"rendered":"<p><a href=\"http:\/\/pfsensesetup.com\/pythonscript.net\/wp-content\/uploads\/2014\/10\/python_logo_3d_by_technopathic-d4qgd9q.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignleft size-medium wp-image-32\" src=\"http:\/\/pfsensesetup.com\/pythonscript.net\/wp-content\/uploads\/2014\/10\/python_logo_3d_by_technopathic-d4qgd9q-300x225.png\" alt=\"exceptions\" width=\"300\" height=\"225\" srcset=\"http:\/\/pfsensesetup.com\/pythonscript.net\/wp-content\/uploads\/2014\/10\/python_logo_3d_by_technopathic-d4qgd9q-300x225.png 300w, http:\/\/pfsensesetup.com\/pythonscript.net\/wp-content\/uploads\/2014\/10\/python_logo_3d_by_technopathic-d4qgd9q.png 800w\" sizes=\"auto, (max-width: 300px) 100vw, 300px\" \/><\/a>As a special case for debugging purposes, Python includes the assert statement; it can be thought of as a conditional raise statement. A statement of the form:<\/p>\n<pre><strong>\tassert , &lt;test&gt; &lt;data&gt;\r\n<\/strong><\/pre>\n<p>works like the following code:<\/p>\n<pre><strong>\tif __debug__:\r\n\t\tif not :\r\n\t\t\traise AssertionError()\r\n<\/strong><\/pre>\n<p>In other words, if the test evaluates to false, Python raises an exception: the data item is used as the exception&#8217;s constructor argument, if a data item is provided. Like all exceptions, the AssertionError exception will kill your program if it&#8217;s not caught with a try, in which case the data item shows up as part of the error message. Otherwsie, AssertionError exceptions can be caught and handled like any other exception.<\/p>\n<p>As an added feature, assert statements may be removed from a compiled program&#8217;s byte code if the -0 Python command-line flag is used, thus optimizing the program (similar to assert statements in C\/C++). AssertionError is a built-in exception, and the __debug__ flag is a built-in name that is automatically set to True unless the -0 flag is used. You can use a command line like python -0 code.py to run in optimized mode and disable asserts.<\/p>\n<p>Assertions are typically used to verify program conditions during development. When displayed, their error message text automatically includes source code line information and the value listed in the assert statement.<\/p>\n<p>As an example, consider a function to convert from Fahrenheit to Celsius. We&#8217;ll make it bail out if it sees a temperature less than absolute zero:<\/p>\n<pre><span style=\"color: #0000ff;\"><strong>def FahrenheitToCelsius(ftemp):\r\n\tassert (ftemp &gt;= -460), \"Less than absolute zero!\"\r\n\treturn ((ftemp-32)*(5.0\/9.0))\r\n\r\nFahrenheitToCelsius(32)\r\nFahrenheitToCelsius(55)\r\nFahrenheitToCelsius(-500)\r\n<\/strong><\/span><\/pre>\n<p>When the above code is executed, it produces the following result:<\/p>\n<pre><strong>0.0\r\n12.777777777777779\r\nTraceback (most recent call last):\r\n  File \"&lt;pyshell#11&gt;\", line 1, in \r\n    FahrenheitToCelsius(-500)\r\n  File \"&lt;pyshell#8&gt;\", line 2, in FahrenheitToCelsius\r\n    assert (ftemp &gt;= -460), \"Less than absolute zero!\"\r\nAssertionError: Less than absolute zero!\r\n<\/strong><\/pre>\n<p>It is important to keep in mind that assert is mostly intended for trapping user-defined constraints and not for catching actual programming errors. Because Python traps programming errors itself, there is usually no need to code asserts to catch things like out-of-bounds indexes, type mismatches, and zero divides. Such asserts are generally unnecessary. Because Python raises exceptions on errors automatically, you can let it do the job for you.<\/p>\n<h3><span style=\"text-decoration: underline;\"><strong>With\/As Clauses<\/strong><\/span><\/h3>\n<p>Python 2.6 and above introduced a new exception-related statement: the <strong>with<\/strong>, and its optional <strong>as<\/strong> clause. This statement is designed to work with context manager objects, which support a new method-based protocol. The <strong>with\/as<\/strong> statement is designed to be an alternative to common try\/finally statements. Like <strong>try\/finally<\/strong>, <strong>with\/as<\/strong> is intended for specifying termination-time or cleanup activity that must run regardless of whether an exception occurs in a processing step. Unlike <strong>try\/finally<\/strong>, the with statement supports a richer object-based protocol for specifying both entry and exit actions around a block of code.<\/p>\n<p>The basic format of the with statement looks like this:<\/p>\n<pre><strong>\twith expression [as variable]:\r\n\t\twith-block\r\n<\/strong><\/pre>\n<p>The expression here is assumed to return an object that supports the context management protocol. This object may also return a value that will be assigned to the name variable if the optional as clause is present.<\/p>\n<p>Note that the variable is not necessarily assigned the result of the expression. The result of the expression is the object that supports the context protocol, and the variable may be assigned something else intended to be used inside the statement. The object returned by the expression may then run startup code before the with-block is started, as well as termination code after the block is done, regardless of whether the block raised an exception or not.<\/p>\n<p>Some built-in Python objects have been augmented to support the context management protocol, and so can be used with the with statement. For example, file objects have a context manager that automatically closes the file after the with block regardless of whether an exception is raised:<\/p>\n<pre><span style=\"color: #0000ff;\"><strong>\twith open(r'file.txt') as myfile:\r\n\t\tfor line in myfile:\r\n\t\t\tprint(line)\r\n<\/strong><\/span><\/pre>\n<p>Here, the call to open returns a simple file object that is assigned to the name myfile. We can use myfile with the usual file tools. In this case, the file iterator reads line by line in the for loop.<\/p>\n<p>But this object also supports the context management protocol used by the with statement. After this with statement has run, the context management machinery guarantees that the file object referenced by myfile is automatically closed, even if the for loop raised an exception while processing the file.<\/p>\n<p>Although file objects are automatically closed on garbage collection, it is not always easy to know when that will occur. The with statement in this role is an alternative that allows us to be sure that the close will occur after execution of a specific block of code. We can accomplish a similar effect with the more general and explicit try\/finally statement, but it requires four lines of code instead of one:<\/p>\n<pre><span style=\"color: #0000ff;\"><strong>\tmyfile = open(r'file.txt')\r\n\ttry:\r\n\t\tfor line in myfile:\r\n\t\t\tprint(line)\r\n\tfinally:\r\n\t\tmyfile.close()\r\n<\/strong><\/span><\/pre>\n<p>The lock and condition synchronization objects they define may also be used with the with statement, because they support the context management protocol:<\/p>\n<pre><strong>\tlock = threading.lock()\r\n\twith lock:\r\n\t# critical code\r\n\t...access shared resources here...\r\n<\/strong><\/pre>\n<p>Here, the context management machinery guarantees that the lock is automatically acquired before the block is executed and released on the block is complete, regardless of exception outcomes.<\/p>\n<p><span style=\"text-decoration: underline;\"><strong>External Links:<\/strong><\/span><\/p>\n<p><a href=\"http:\/\/www.tutorialspoint.com\/python\/assertions_in_python.htm\">Assertions in Python at www.tutorialspoint.com<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>As a special case for debugging purposes, Python includes the assert statement; it can be thought of as a conditional raise statement. A statement of the form: assert , &lt;test&gt; &lt;data&gt; works like the following code: if __debug__: if not : raise AssertionError() In other words, if the test evaluates to false, Python raises an [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[7,3],"tags":[79,69,81,4,80],"class_list":["post-119","post","type-post","status-publish","format-standard","hentry","category-guides","category-tutorials","tag-assert","tag-exceptions","tag-lock","tag-python","tag-with-as","entry"],"_links":{"self":[{"href":"http:\/\/pfsensesetup.com\/pythonscript.net\/wp-json\/wp\/v2\/posts\/119","targetHints":{"allow":["GET"]}}],"collection":[{"href":"http:\/\/pfsensesetup.com\/pythonscript.net\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/pfsensesetup.com\/pythonscript.net\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/pfsensesetup.com\/pythonscript.net\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"http:\/\/pfsensesetup.com\/pythonscript.net\/wp-json\/wp\/v2\/comments?post=119"}],"version-history":[{"count":1,"href":"http:\/\/pfsensesetup.com\/pythonscript.net\/wp-json\/wp\/v2\/posts\/119\/revisions"}],"predecessor-version":[{"id":120,"href":"http:\/\/pfsensesetup.com\/pythonscript.net\/wp-json\/wp\/v2\/posts\/119\/revisions\/120"}],"wp:attachment":[{"href":"http:\/\/pfsensesetup.com\/pythonscript.net\/wp-json\/wp\/v2\/media?parent=119"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/pfsensesetup.com\/pythonscript.net\/wp-json\/wp\/v2\/categories?post=119"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/pfsensesetup.com\/pythonscript.net\/wp-json\/wp\/v2\/tags?post=119"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}