Popular recipes tagged "meta:min_python_3=0"http://code.activestate.com/recipes/tags/meta:min_python_3=0/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>
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>
groupby() For Unsorted Input (Python)
2017-05-12T10:40:58-07:00Alfehttp://code.activestate.com/recipes/users/4182236/http://code.activestate.com/recipes/580800-groupby-for-unsorted-input/
<p style="color: grey">
Python
recipe 580800
by <a href="/recipes/users/4182236/">Alfe</a>
(<a href="/recipes/tags/algorithm/">algorithm</a>, <a href="/recipes/tags/datastructures/">datastructures</a>, <a href="/recipes/tags/generators/">generators</a>, <a href="/recipes/tags/grouping/">grouping</a>, <a href="/recipes/tags/lazy/">lazy</a>).
</p>
<p>We all know the <code>groupby()</code> which is available in the <code>itertools</code> standard module. This one yields groups of consecutive elements in the input which are meant to be together in one group. For non-consecutive elements this will yield more than one group for the same key.</p>
<p>So effectively, <code>groupby()</code> only reformats a flat list into bunches of elements from that list without reordering anything. In practice this means that for input sorted by key this works perfect, but for unsorted input it might yield several groups for the same key (with groups for other keys in between). Typically needed, though, is a grouping with reordering if necessary.</p>
<p>I implemented a likewise lazy function (yielding generators) which also accepts ungrouped input.</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>
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>
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>
ctypes CDLL with automatic errno checking (Python)
2017-01-03T10:31:26-08:00Oren Tiroshhttp://code.activestate.com/recipes/users/2033964/http://code.activestate.com/recipes/580741-ctypes-cdll-with-automatic-errno-checking/
<p style="color: grey">
Python
recipe 580741
by <a href="/recipes/users/2033964/">Oren Tirosh</a>
.
</p>
<p>This class extends ctypes.CDLL with automatic checking of errno and automatically raises an exception when set by the function.</p>
States to Regions (Python)
2016-05-09T22:24:26-07:00Jackson Killianhttp://code.activestate.com/recipes/users/4194060/http://code.activestate.com/recipes/580661-states-to-regions/
<p style="color: grey">
Python
recipe 580661
by <a href="/recipes/users/4194060/">Jackson Killian</a>
(<a href="/recipes/tags/dictionary/">dictionary</a>, <a href="/recipes/tags/regions/">regions</a>, <a href="/recipes/tags/states/">states</a>).
</p>
<p>Python dictionary mapping two letter state abbreviations to their respective regions of the country (i.e. Midwest, North East, etc.)
N - North East
W - West
M - Mid West
S - South
O - Other</p>
Auto differentiation (Python)
2016-08-07T22:02:10-07:00Raymond Hettingerhttp://code.activestate.com/recipes/users/178123/http://code.activestate.com/recipes/580610-auto-differentiation/
<p style="color: grey">
Python
recipe 580610
by <a href="/recipes/users/178123/">Raymond Hettinger</a>
(<a href="/recipes/tags/autodifferentiation/">autodifferentiation</a>, <a href="/recipes/tags/calculus/">calculus</a>, <a href="/recipes/tags/descent/">descent</a>, <a href="/recipes/tags/gradient/">gradient</a>, <a href="/recipes/tags/math/">math</a>, <a href="/recipes/tags/optimization/">optimization</a>, <a href="/recipes/tags/vector/">vector</a>).
Revision 5.
</p>
<p>Directly computes derivatives from ordinary Python functions using auto differentiation. The technique directly computes the desired derivatives to full precision without resorting to symbolic math and without making estimates bases on numerical methods.</p>
<p>The module provides a Num class for "dual" numbers that performs both regular floating point math on a value and its derivative at the same time. In addition, the module provides drop-in substitutes for most of the functions in the math module. There are also tools for partial derivatives, directional derivatives, gradients of scalar fields, and the curl and divergence of vector fields.</p>
Simple Matlab/Ocave like arrays conversion to numpy.arrays in python interpreter (Python)
2016-09-22T12:25:30-07:00Przemyslaw Podczasihttp://code.activestate.com/recipes/users/4179716/http://code.activestate.com/recipes/580700-simple-matlabocave-like-arrays-conversion-to-numpy/
<p style="color: grey">
Python
recipe 580700
by <a href="/recipes/users/4179716/">Przemyslaw Podczasi</a>
(<a href="/recipes/tags/array/">array</a>, <a href="/recipes/tags/interpreter/">interpreter</a>, <a href="/recipes/tags/matlab/">matlab</a>).
</p>
<p>Matlab/Octave syntax for 1D/2D arrays is more packed and doesn't require putting extra ',' and extra '[', ']' between dimensions.
For this I wrote a parser that intercepts python interpreter and using numpy functionality parses Matlab's style arrays 1D and 2D into numpy.arrays.</p>
convert hierarchy of data files into a convenient Python dictionary (Python)
2016-06-29T20:09:44-07:00Brian Fiedlerhttp://code.activestate.com/recipes/users/4194196/http://code.activestate.com/recipes/580687-convert-hierarchy-of-data-files-into-a-convenient-/
<p style="color: grey">
Python
recipe 580687
by <a href="/recipes/users/4194196/">Brian Fiedler</a>
(<a href="/recipes/tags/pickle/">pickle</a>).
Revision 2.
</p>
<p>Converts the CRUTEM text data files into a convenient Python dictionary.
The data files are at:
<a href="http://www.metoffice.gov.uk/hadobs/crutem4/data/station_files/CRUTEM.4.4.0.0.station_files.zip" rel="nofollow">http://www.metoffice.gov.uk/hadobs/crutem4/data/station_files/CRUTEM.4.4.0.0.station_files.zip</a></p>
PyOOCalc - Python Libre/Open Office Calc Interface API (UNO) (Python)
2016-01-10T13:12:53-08:00Yuriihttp://code.activestate.com/recipes/users/4193384/http://code.activestate.com/recipes/579147-pyoocalc-python-libreopen-office-calc-interface-ap/
<p style="color: grey">
Python
recipe 579147
by <a href="/recipes/users/4193384/">Yurii</a>
(<a href="/recipes/tags/openoffice/">openoffice</a>, <a href="/recipes/tags/python/">python</a>, <a href="/recipes/tags/python3/">python3</a>).
</p>
<p>Create Libre/Open Office Calc documents, reports on Python</p>
Batch download all the pinned pictures in your Pinterest board to a local folder (Python)
2016-02-18T17:26:50-08:00Alfred Wanghttp://code.activestate.com/recipes/users/4193275/http://code.activestate.com/recipes/580611-batch-download-all-the-pinned-pictures-in-your-pin/
<p style="color: grey">
Python
recipe 580611
by <a href="/recipes/users/4193275/">Alfred Wang</a>
(<a href="/recipes/tags/batch/">batch</a>, <a href="/recipes/tags/download/">download</a>, <a href="/recipes/tags/picture/">picture</a>, <a href="/recipes/tags/pinterest/">pinterest</a>).
</p>
<p>Batch download all the pinned pictures in your Pinterest board to a local folder.
Be noted: you have to keep your internet browser signed in your Pinterest account first.</p>
How to build dobble as a Mixed Integer program. (Python)
2016-04-13T11:53:21-07:00alexander bakerhttp://code.activestate.com/recipes/users/4166679/http://code.activestate.com/recipes/580641-how-to-build-dobble-as-a-mixed-integer-program/
<p style="color: grey">
Python
recipe 580641
by <a href="/recipes/users/4166679/">alexander baker</a>
(<a href="/recipes/tags/integer/">integer</a>, <a href="/recipes/tags/interface/">interface</a>, <a href="/recipes/tags/mixed/">mixed</a>, <a href="/recipes/tags/program/">program</a>).
</p>
<p>A simple script to replicate the cards and symbols for the dobble game.</p>
[python3-tk/ttk] Onager Scratchpad (Python)
2016-04-24T02:34:03-07:00Mickey Kocichttp://code.activestate.com/recipes/users/4193984/http://code.activestate.com/recipes/580650-python3-tkttk-onager-scratchpad/
<p style="color: grey">
Python
recipe 580650
by <a href="/recipes/users/4193984/">Mickey Kocic</a>
(<a href="/recipes/tags/python3/">python3</a>, <a href="/recipes/tags/text_processing/">text_processing</a>, <a href="/recipes/tags/tkinter/">tkinter</a>, <a href="/recipes/tags/ttk/">ttk</a>, <a href="/recipes/tags/windows/">windows</a>).
Revision 2.
</p>
<p>I wrote this simple text editor to use for my diary. It's customized the way I like it, but the code is set up so it's easy for other people to change bg, fg, font, etc. I've also compiled a standalone Windows executable (thank you very much ActiveState! without ActivePython the compilation would have been impossible). Anyone who wants a copy of the executable is free to message or email me.</p>
<p>NOTE: If you get an error that the theme is not recognized, just comment out line 18 or run the following code in your python3 interpreter:</p>
<pre class="prettyprint"><code>>>>from tkinter.ttk import Style
>>>s = Style()
>>>s.theme_use()
</code></pre>
<p>You'll get a list of the available themes and can replace the 'alt' in line 18 with any one of them you want.</p>
Python2 keyword-only argument emulation as a decorator. Python3 compatible. (Python)
2016-04-15T13:25:20-07:00István Pásztorhttp://code.activestate.com/recipes/users/4189380/http://code.activestate.com/recipes/580639-python2-keyword-only-argument-emulation-as-a-decor/
<p style="color: grey">
Python
recipe 580639
by <a href="/recipes/users/4189380/">István Pásztor</a>
(<a href="/recipes/tags/args/">args</a>, <a href="/recipes/tags/arguments/">arguments</a>, <a href="/recipes/tags/keyword/">keyword</a>, <a href="/recipes/tags/keyword_only/">keyword_only</a>, <a href="/recipes/tags/kwonly/">kwonly</a>, <a href="/recipes/tags/only/">only</a>, <a href="/recipes/tags/python2/">python2</a>).
Revision 4.
</p>
<p>Provides a very simple decorator (~40 lines of code) that can turn some or all of your default arguments into keyword-only arguments. You select one of your default arguments by name and the decorator turn this argument along with all default arguments on its right side into keyword only arguments. Check the docstring of the decorator or visit the github/pypi page for detailed documentation:</p>
<ul>
<li><a href="https://github.com/pasztorpisti/kwonly-args" rel="nofollow">https://github.com/pasztorpisti/kwonly-args</a></li>
<li><a href="https://pypi.python.org/pypi/kwonly-args" rel="nofollow">https://pypi.python.org/pypi/kwonly-args</a></li>
</ul>
<p><code>$ pip install kwonly-args</code></p>
Catalog multiple drives (Python)
2016-03-11T03:39:32-08:00Jack Trainorhttp://code.activestate.com/recipes/users/4076953/http://code.activestate.com/recipes/580619-catalog-multiple-drives/
<p style="color: grey">
Python
recipe 580619
by <a href="/recipes/users/4076953/">Jack Trainor</a>
(<a href="/recipes/tags/drives/">drives</a>, <a href="/recipes/tags/files/">files</a>, <a href="/recipes/tags/utility/">utility</a>).
</p>
<p>As one accumulates multiple drives, hard and flash, containing,
thousands even millions of files, it becomes useful to have a text file
containing an alphabetized catalog list of all files and their locations
by drive and directory.</p>
<p>The list can be searched by eye or by an editor to locate particular
files.</p>
<p>The list can also be loaded into a script to be filtered
programmatically as desired.</p>
FileSpec: Set it, forget it, reuse it (Python)
2016-03-08T05:49:16-08:00Jack Trainorhttp://code.activestate.com/recipes/users/4076953/http://code.activestate.com/recipes/580618-filespec-set-it-forget-it-reuse-it/
<p style="color: grey">
Python
recipe 580618
by <a href="/recipes/users/4076953/">Jack Trainor</a>
(<a href="/recipes/tags/filename/">filename</a>, <a href="/recipes/tags/utilities/">utilities</a>).
</p>
<p>Python provides good utilities for transforming filenames, but they are tedious to use and clutter up the source code.</p>
<p>FileSpec offers one-stop shopping to convert a file path to every component you might want to know, reuse, or transform.</p>