Popular recipes tagged "meta:min_python_3=*" but not "algorithm" and "tkinter"http://code.activestate.com/recipes/tags/meta:min_python_3=*-algorithm-tkinter/2017-07-17T05:53:45-07:00ActiveState Code RecipesUno (Text-Based) (Python) 2017-07-15T00:46:59-07:00Brandon Martinhttp://code.activestate.com/recipes/users/4194238/http://code.activestate.com/recipes/580811-uno-text-based/ <p style="color: grey"> Python recipe 580811 by <a href="/recipes/users/4194238/">Brandon Martin</a> (<a href="/recipes/tags/artificial_intelligence/">artificial_intelligence</a>, <a href="/recipes/tags/cards/">cards</a>, <a href="/recipes/tags/game/">game</a>, <a href="/recipes/tags/text_game/">text_game</a>, <a href="/recipes/tags/uno/">uno</a>). </p> <p>A text based recreation of the classic card game featuring functional AIs to play with. Some rules have been modified. User interface is text based, non-curses, using only simple python commands to draw it. </p> Equally-spaced numbers (linspace) (Python) 2015-01-12T22:16:37-08:00Andrew Barnerthttp://code.activestate.com/recipes/users/4184316/http://code.activestate.com/recipes/579000-equally-spaced-numbers-linspace/ <p style="color: grey"> Python recipe 579000 by <a href="/recipes/users/4184316/">Andrew Barnert</a> (<a href="/recipes/tags/float/">float</a>, <a href="/recipes/tags/linspace/">linspace</a>, <a href="/recipes/tags/range/">range</a>, <a href="/recipes/tags/spread/">spread</a>). </p> <p>An equivalent of <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.linspace.html"><code>numpy.linspace</code></a>, but as a pure-Python lazy sequence.</p> <p>Like NumPy's <code>linspace</code>, but unlike the <a href="http://code.activestate.com/recipes/577068/"><code>spread</code></a> and <a href="http://code.activestate.com/recipes/577068/"><code>frange</code></a> recipes listed here, the <code>num</code> argument specifies the number of values, not the number of intervals, and the range is closed, not half-open.</p> <p>Although this is primarily designed for floats, it will work for <code>Fraction</code>, <code>Decimal</code>, NumPy arrays (although this would be silly) and even <code>datetime</code> values.</p> <p>This recipe can also serve as an example for creating lazy sequences.</p> <p>See the discussion below for caveats.</p> Shoelace Formula for polygonal area (Python) 2017-07-17T05:53:45-07:00Paddy McCarthyhttp://code.activestate.com/recipes/users/398009/http://code.activestate.com/recipes/580812-shoelace-formula-for-polygonal-area/ <p style="color: grey"> Python recipe 580812 by <a href="/recipes/users/398009/">Paddy McCarthy</a> (<a href="/recipes/tags/2d/">2d</a>, <a href="/recipes/tags/area/">area</a>). </p> <p>Copied, by author from "Paddy3118 Go deh!: Python investigation of the Shoelace Formula for polygonal area <a href="http://paddy3118.blogspot.com/2017/07/python-investigation-of-shoelace.html#ixzz4n43Dqhaa" rel="nofollow">http://paddy3118.blogspot.com/2017/07/python-investigation-of-shoelace.html#ixzz4n43Dqhaa</a> " Where there is more meat on the bone (under a different license though).</p> PDF Text Extraction using fitz / MuPDF (PyMuPDF) (Python) 2016-03-17T12:00:06-07:00Jorj X. McKiehttp://code.activestate.com/recipes/users/4193772/http://code.activestate.com/recipes/580626-pdf-text-extraction-using-fitz-mupdf-pymupdf/ <p style="color: grey"> Python recipe 580626 by <a href="/recipes/users/4193772/">Jorj X. McKie</a> (<a href="/recipes/tags/cbz/">cbz</a>, <a href="/recipes/tags/epub/">epub</a>, <a href="/recipes/tags/mupdf/">mupdf</a>, <a href="/recipes/tags/openxps/">openxps</a>, <a href="/recipes/tags/pdf/">pdf</a>, <a href="/recipes/tags/pymupdf/">pymupdf</a>, <a href="/recipes/tags/text_extraction/">text_extraction</a>, <a href="/recipes/tags/xps/">xps</a>). </p> <p>Extract all the text of a PDF (or other supported container types) at very high speed. In general, text pieces of a PDF page are not arranged in natural reading order, but in the order they were entered during PDF creation. This script re-arranges text blocks according to their pixel coordinates to achieve a more readable output, i.e. top-down, left-right.</p> Variable Abbreviations (Python) 2017-06-22T11:57:20-07:00Alfehttp://code.activestate.com/recipes/users/4182236/http://code.activestate.com/recipes/580807-variable-abbreviations/ <p style="color: grey"> Python recipe 580807 by <a href="/recipes/users/4182236/">Alfe</a> (<a href="/recipes/tags/abbreviations/">abbreviations</a>, <a href="/recipes/tags/contextmanager/">contextmanager</a>, <a href="/recipes/tags/variables/">variables</a>, <a href="/recipes/tags/with/">with</a>). </p> <p>One sometimes has nice long speaking names vor variables, maybe things like <code>buildingList[foundIndex].height</code>, but would like to address these in a shorter fashion to be used within a formula or similar where lots of longs names tend to confuse any reader trying to understand the formula. Physicists use one-letter names for a reason.</p> <p>For this I wrote a small context provider which allows using short names instead of long ones:</p> <pre class="prettyprint"><code>with Abbr(h=buildingList[foundIndex].height, g=gravitationalConstant): fallTime = sqrt(2 * h / g) endSpeed = sqrt(2 * h * g) print("Fall time:", fallTime) print("End speed:", endSpeed) </code></pre> <p>For longer formulas this can reduce ugly multi-line expressions to clearly readable one-liners.</p> <p>One could use this:</p> <pre class="prettyprint"><code>h = buildingList[foundIndex].height g = gravitationalConstant fallTime = sqrt(2 * h / g) endSpeed = sqrt(2 * h * g) del g, h print("Fall time:", fallTime) print("End speed:", endSpeed) </code></pre> <p>to achieve the same result, but</p> <ul> <li>it would not look as clean and</li> <li>the context provider solves the typical issues like cleanup on exception etc.</li> </ul> <p>Just using local variables without cleanup (like above without the <code>del</code> statement) also is an option of course, but that would clutter the variable name space unnecessarily.</p> <p>CAVEATS: The implementation of <code>Abbr()</code> is a hack. If used as intended and described here, it should work just fine, though. But the hackish nature forces me to mention some things: Since at compile time the compiler decides that the <code>h</code> and <code>g</code> in the example must be global variables (because they aren't assigned in the function), it produces byte code accessing global variables. The context provider changes the global variable structure to fill the needs. (Overridden already existing global variables of the same name get restored properly at context exit.) This means some things:</p> <ul> <li>One cannot have a local variable of the same name in the frame surrounding the context manager.</li> <li>Existing global variables are changed during the time of the context manager; so using names like <code>sys</code> or <code>os</code> for abbreviations might be a bad idea due to side-effects.</li> </ul> Guard against an exception in the wrong place (Python) 2017-06-25T17:17:43-07:00Steven D'Apranohttp://code.activestate.com/recipes/users/4172944/http://code.activestate.com/recipes/580808-guard-against-an-exception-in-the-wrong-place/ <p style="color: grey"> Python recipe 580808 by <a href="/recipes/users/4172944/">Steven D'Aprano</a> (<a href="/recipes/tags/context/">context</a>, <a href="/recipes/tags/exception/">exception</a>, <a href="/recipes/tags/guard/">guard</a>, <a href="/recipes/tags/manager/">manager</a>). Revision 2. </p> <p>Sometimes exception handling can obscure bugs unless you guard against a particular exception occurring in a certain place. One example is that <a href="https://www.python.org/dev/peps/pep-0479/">accidentally raising <code>StopIteration</code> inside a generator</a> will halt the generator instead of displaying a traceback. That was solved by PEP 479, which automatically has such <code>StopIteration</code> exceptions change to <code>RuntimeError</code>. See the discussion below for further examples.</p> <p>Here is a class which can be used as either a decorator or context manager for guarding against the given exceptions. It takes an exception (or a tuple of exceptions) as argument, and if the wrapped code raises that exception, it is re-raised as another exception type (by default <code>RuntimeError</code>).</p> <p>For example:</p> <pre class="prettyprint"><code>try: with exception_guard(ZeroDivisionError): 1/0 # raises ZeroDivisionError except RuntimeError: print ('ZeroDivisionError replaced by RuntimeError') @exception_guard(KeyError) def demo(): return {}['key'] # raises KeyError try: demo() except RuntimeError: print ('KeyError replaced by RuntimeError') </code></pre> Unit Testing Nested Functions (Python) 2016-11-10T10:23:11-08:00Alfehttp://code.activestate.com/recipes/users/4182236/http://code.activestate.com/recipes/580716-unit-testing-nested-functions/ <p style="color: grey"> Python recipe 580716 by <a href="/recipes/users/4182236/">Alfe</a> (<a href="/recipes/tags/introspection/">introspection</a>, <a href="/recipes/tags/nested/">nested</a>, <a href="/recipes/tags/unittests/">unittests</a>). Revision 3. </p> <p>Python allows the declaration of nested functions. These are typically hard to unit test because using just the normal ways of calling they cannot be called from outside their surrounding function. So they cannot be considered a clearly separated unit and thus cannot be unit tested.</p> <p>This is a drawback of using them, so many developers (especially the ones deep into test driven development who strive to have a high unit test coverage) tend to avoid them in favor for standalone functions which can be called from the unit tests without any hassle.</p> <p>But not all solutions with nested functions can be written as elegant with standalone functions. Nested functions are powerful insofar that they can access the local variables of the surrounding function without any need to pass them into the nested function, thus the code can in many cases stay neat and tidy while using a standalone function instead might raise the need to pass the complete context in form of a bunch of parameters. Also, using nested functions makes their local usage clear to any reader and keeps the name space tight.</p> <p>But at least in the standard CPython (i. e. not necessarily in Jython, etc.) the implementation of functions (and methods) allows to find the nested function's code, wrap it properly to give it its needed context and then call it from the outside. I wrote a small module which helps doing exactly this.</p> Lines Of Code (LOC) (Python) 2016-10-25T17:53:01-07:00Jean Brouwershttp://code.activestate.com/recipes/users/2984142/http://code.activestate.com/recipes/580709-lines-of-code-loc/ <p style="color: grey"> Python recipe 580709 by <a href="/recipes/users/2984142/">Jean Brouwers</a> (<a href="/recipes/tags/count/">count</a>, <a href="/recipes/tags/lines/">lines</a>, <a href="/recipes/tags/python2/">python2</a>, <a href="/recipes/tags/python3/">python3</a>, <a href="/recipes/tags/source/">source</a>). Revision 3. </p> <p>Count the number of lines (code, comment, blank) in one or several Python source files.</p> Rotate a PDF page in 3 lines (Python) 2016-11-06T11:33:59-08:00Jorj X. McKiehttp://code.activestate.com/recipes/users/4193772/http://code.activestate.com/recipes/580713-rotate-a-pdf-page-in-3-lines/ <p style="color: grey"> Python recipe 580713 by <a href="/recipes/users/4193772/">Jorj X. McKie</a> (<a href="/recipes/tags/fitz/">fitz</a>, <a href="/recipes/tags/mupdf/">mupdf</a>, <a href="/recipes/tags/pdf/">pdf</a>, <a href="/recipes/tags/pymupdf/">pymupdf</a>). Revision 2. </p> <p>PyMuPDF v1.9.3 now supports several new features for manipulating PDFs.</p> <p>Here is an example to rotate a page with just a few lines of Python code.</p> How to delete pages in a PDF using fitz / MuPDF / PyMuPDF (Python) 2016-05-01T09:26:44-07:00Jorj X. McKiehttp://code.activestate.com/recipes/users/4193772/http://code.activestate.com/recipes/580657-how-to-delete-pages-in-a-pdf-using-fitz-mupdf-pymu/ <p style="color: grey"> Python recipe 580657 by <a href="/recipes/users/4193772/">Jorj X. McKie</a> (<a href="/recipes/tags/mupdf/">mupdf</a>, <a href="/recipes/tags/pdf/">pdf</a>, <a href="/recipes/tags/pdf_generation/">pdf_generation</a>). </p> <p>A new method <strong>select()</strong> in PyMuPDF 1.9.0 allows selecting pages of a PDF document to create a new one. Any Python list of integers (0 &lt;= n &lt; page count) can be taken.</p> <p>The resulting PDF contains all links, annotations and bookmarks (provided they still point to valid targets).</p> Retry Decorator in Python (Python) 2017-01-11T10:10:30-08:00Alfehttp://code.activestate.com/recipes/users/4182236/http://code.activestate.com/recipes/580745-retry-decorator-in-python/ <p style="color: grey"> Python recipe 580745 by <a href="/recipes/users/4182236/">Alfe</a> (<a href="/recipes/tags/aspect/">aspect</a>, <a href="/recipes/tags/except/">except</a>, <a href="/recipes/tags/exception/">exception</a>, <a href="/recipes/tags/retry/">retry</a>, <a href="/recipes/tags/try/">try</a>). </p> <p>This is a Python decorator which helps implementing an aspect oriented implementation of a <em>retrying</em> of certain steps which might fail sometimes. A typical example for this would be communication processes with the outside world, e. g. HTTP requests, allocation of some resource, etc. To use it, refactor the step in question into a (local) function and decorate this with the <code>retry</code> decorator. See examples in the discussion sector below.</p> TicTacToe (text based) (Python) 2016-11-27T07:10:56-08:00Brandon Martinhttp://code.activestate.com/recipes/users/4194238/http://code.activestate.com/recipes/580723-tictactoe-text-based/ <p style="color: grey"> Python recipe 580723 by <a href="/recipes/users/4194238/">Brandon Martin</a> (<a href="/recipes/tags/artificial_intelligence/">artificial_intelligence</a>, <a href="/recipes/tags/game/">game</a>, <a href="/recipes/tags/python/">python</a>, <a href="/recipes/tags/random/">random</a>, <a href="/recipes/tags/tac/">tac</a>, <a href="/recipes/tags/tic/">tic</a>, <a href="/recipes/tags/tictactoe/">tictactoe</a>, <a href="/recipes/tags/toe/">toe</a>). </p> <p>A text based version of TicTacToe for Python. Difficulty is not yet implemented, however, a computer player has been implemented that cannot be beaten. Posting just for fun.</p> Context Manager for an Arbitrary Number of Files in Python (Python) 2017-03-13T13:27:50-07:00Alfehttp://code.activestate.com/recipes/users/4182236/http://code.activestate.com/recipes/580763-context-manager-for-an-arbitrary-number-of-files-i/ <p style="color: grey"> Python recipe 580763 by <a href="/recipes/users/4182236/">Alfe</a> (<a href="/recipes/tags/contextmanager/">contextmanager</a>, <a href="/recipes/tags/file/">file</a>, <a href="/recipes/tags/open/">open</a>). Revision 2. </p> <p>The pattern using <code>with</code> together with <code>open()</code> to automatically close a file after leaving the context is well known. To open a fixed number you can simply nest these statements or use the comma notation. For having a context which represents an arbitrary number of open files you can use the <code>ExitStack</code> class, but only for Python 3.3+.</p> <p>For other Python versions I'm using the following class which I named <code>Files</code>. The presented implementation is only for reading files (for keeping it clear). Extending it for having various file modes should not pose a problem.</p> How to parse a table in a PDF document (Python) 2016-04-10T22:43:57-07:00Jorj X. McKiehttp://code.activestate.com/recipes/users/4193772/http://code.activestate.com/recipes/580635-how-to-parse-a-table-in-a-pdf-document/ <p style="color: grey"> Python recipe 580635 by <a href="/recipes/users/4193772/">Jorj X. McKie</a> (<a href="/recipes/tags/cbz/">cbz</a>, <a href="/recipes/tags/epub/">epub</a>, <a href="/recipes/tags/fitz/">fitz</a>, <a href="/recipes/tags/mupdf/">mupdf</a>, <a href="/recipes/tags/openxps/">openxps</a>, <a href="/recipes/tags/parsing/">parsing</a>, <a href="/recipes/tags/pdf/">pdf</a>, <a href="/recipes/tags/pymupdf/">pymupdf</a>, <a href="/recipes/tags/table/">table</a>, <a href="/recipes/tags/xps/">xps</a>). Revision 4. </p> <p>A Python function that converts a table contained in a page of a PDF (or OpenXPS, EPUB, CBZ, XPS) document to a matrix-like Python object (list of lists of strings).</p> Simple signal library, similar to PyQT signals (Python) 2017-04-01T21:11:50-07:00Miguel Martínez Lópezhttp://code.activestate.com/recipes/users/4189907/http://code.activestate.com/recipes/580764-simple-signal-library-similar-to-pyqt-signals/ <p style="color: grey"> Python recipe 580764 by <a href="/recipes/users/4189907/">Miguel Martínez López</a> (<a href="/recipes/tags/event/">event</a>, <a href="/recipes/tags/pubsub/">pubsub</a>, <a href="/recipes/tags/signal/">signal</a>). Revision 11. </p> <p>Simple signal library similar to PyQT signals. Signals helps to decouple code in GUI applications. This code could be used in Tkinter applications for example.</p> <p>Inspired and based in these other modules:</p> <p><a href="https://github.com/shaunduncan/smokesignal" rel="nofollow">https://github.com/shaunduncan/smokesignal</a></p> <p><a href="https://github.com/dgovil/PySignal" rel="nofollow">https://github.com/dgovil/PySignal</a></p> <p><a href="https://github.com/jek/blinker" rel="nofollow">https://github.com/jek/blinker</a></p> Easily create a Python REPL in Python (Python) 2016-10-31T21:53:30-07:00Vasudev Ramhttp://code.activestate.com/recipes/users/4173351/http://code.activestate.com/recipes/580712-easily-create-a-python-repl-in-python/ <p style="color: grey"> Python recipe 580712 by <a href="/recipes/users/4173351/">Vasudev Ram</a> (<a href="/recipes/tags/code_module/">code_module</a>, <a href="/recipes/tags/dynamic/">dynamic</a>, <a href="/recipes/tags/evaluation/">evaluation</a>, <a href="/recipes/tags/read_eval_print_loop/">read_eval_print_loop</a>, <a href="/recipes/tags/repl/">repl</a>). </p> <p>This recipe shows how to easily create a Python REPL (Read-Eval-Print Loop) in Python itself. This can allow the user to interact with a running Python program, including typing in Python statements at the REPL prompt, defining functions, using and changing variables that were set before the interaction started, and those variables modified during the interaction, will persist in the memory of the program, for any use, even after the interaction is over, as long as the program continues to run.</p> Python add/set attributes to list (Python) 2015-09-29T16:28:46-07:00webby1111http://code.activestate.com/recipes/users/4192908/http://code.activestate.com/recipes/579103-python-addset-attributes-to-list/ <p style="color: grey"> Python recipe 579103 by <a href="/recipes/users/4192908/">webby1111</a> (<a href="/recipes/tags/attributes/">attributes</a>, <a href="/recipes/tags/class/">class</a>, <a href="/recipes/tags/dictionary/">dictionary</a>, <a href="/recipes/tags/list/">list</a>, <a href="/recipes/tags/subclass/">subclass</a>). Revision 3. </p> <h4 id="python-attribute-listhttpsgithubcomwebby1111python-attribute-list"><a href="https://github.com/webby1111/Python-Attribute-List">Python Attribute List</a></h4> <p>Add/set attributes to python lists.</p> <p>A google search for "add attributes to python lists" yields no good stackoverflow answer, hence the need for this.</p> <p>Useful for machine learning stuff where you need labeled feature vectors. </p> <p>This technique can be easily adapted for other built-ins (e.g. int).</p> <h5 id="the-problem">The Problem</h5> <pre class="prettyprint"><code>a = [1, 2, 4, 8] a.x = "Hey!" # AttributeError: 'list' object has no attribute 'x' </code></pre> <h5 id="the-solution">The Solution</h5> <pre class="prettyprint"><code>a = L(1, 2, 4, 8) a.x = "Hey!" print a # [1, 2, 4, 8] print a.x # "Hey!" print len(a) # 4 # You can also do these: a = L( 1, 2, 4, 8 , x="Hey!" ) # [1, 2, 4, 8] a = L( 1, 2, 4, 8 )( x="Hey!" ) # [1, 2, 4, 8] a = L( [1, 2, 4, 8] , x="Hey!" ) # [1, 2, 4, 8] a = L( {1, 2, 4, 8} , x="Hey!" ) # [1, 2, 4, 8] a = L( [2 ** b for b in range(4)] , x="Hey!" ) # [1, 2, 4, 8] a = L( (2 ** b for b in range(4)) , x="Hey!" ) # [1, 2, 4, 8] a = L( 2 ** b for b in range(4) )( x="Hey!" ) # [1, 2, 4, 8] a = L( 2 ) # [2] </code></pre> Compute Memory footprint of an object and its contents (Python) 2012-11-23T23:57:31-08:00Raymond Hettingerhttp://code.activestate.com/recipes/users/178123/http://code.activestate.com/recipes/577504-compute-memory-footprint-of-an-object-and-its-cont/ <p style="color: grey"> Python recipe 577504 by <a href="/recipes/users/178123/">Raymond Hettinger</a> (<a href="/recipes/tags/memory/">memory</a>, <a href="/recipes/tags/sizeof/">sizeof</a>). Revision 3. </p> <p>Recursive version sys.getsizeof(). Extendable with custom handlers.</p> Give Python code a web plus command-line interface with hug (Python) 2017-01-05T16:57:15-08:00Vasudev Ramhttp://code.activestate.com/recipes/users/4173351/http://code.activestate.com/recipes/580742-give-python-code-a-web-plus-command-line-interface/ <p style="color: grey"> Python recipe 580742 by <a href="/recipes/users/4173351/">Vasudev Ram</a> (<a href="/recipes/tags/cli/">cli</a>, <a href="/recipes/tags/commandline/">commandline</a>, <a href="/recipes/tags/hug/">hug</a>, <a href="/recipes/tags/library/">library</a>, <a href="/recipes/tags/python/">python</a>, <a href="/recipes/tags/python3/">python3</a>, <a href="/recipes/tags/user_interface/">user_interface</a>, <a href="/recipes/tags/web/">web</a>, <a href="/recipes/tags/web_server/">web_server</a>). </p> <p>This recipe shows how to take a Python function and wrap it with both a web and a command-line interface, somewhat easily, using the hug Python library. The example used shows how to wrap a function that uses the psutil library to get information on disk partitions. So you can see the disk partition info either via the web browser or the command line. The code for the recipe is shown below. It is also possible to wrap multiple functions in the same Python file, and expose all of them via both the web and the command-line.</p> <p>More information and multiple sample outputs are available here:</p> <p><a href="https://jugad2.blogspot.in/2017/01/give-your-python-function-webcli-hug.html" rel="nofollow">https://jugad2.blogspot.in/2017/01/give-your-python-function-webcli-hug.html</a></p> Get names and types of all attributes of a Python module (Python) 2016-10-06T17:21:42-07:00Vasudev Ramhttp://code.activestate.com/recipes/users/4173351/http://code.activestate.com/recipes/580705-get-names-and-types-of-all-attributes-of-a-python-/ <p style="color: grey"> Python recipe 580705 by <a href="/recipes/users/4173351/">Vasudev Ram</a> (<a href="/recipes/tags/documentation/">documentation</a>, <a href="/recipes/tags/introspection/">introspection</a>, <a href="/recipes/tags/modules/">modules</a>, <a href="/recipes/tags/reflection/">reflection</a>, <a href="/recipes/tags/type/">type</a>). </p> <p>This recipe shows how to get the names and types of all the attributes of a Python module. This can be useful when exploring new modules (either built-in or third-party), because attributes are mostly a) data elements or b) functions or methods, and for either of those, you would like to know the type of the attribute, so that, if it is a data element, you can print it, and if it is a function or method, you can print its docstring to get brief help on its arguments, processsing and outputs or return values, as a way of learning how to use it.</p> <p>The code for the recipe includes an example call to it, at the end of the code. Note that you first have to import the modules that you want to introspect in this way.</p>