Popular Python recipes tagged "meta:requires=inspect"http://code.activestate.com/recipes/langs/python/tags/meta:requires=inspect/2017-04-26T17:26:29-07:00ActiveState Code RecipesAuto assign self attributes in __init__ using PEP 484 (Python)
2017-04-26T17:26:29-07:00Ryan Gonzalezhttp://code.activestate.com/recipes/users/4187447/http://code.activestate.com/recipes/580790-auto-assign-self-attributes-in-__init__-using-pep-/
<p style="color: grey">
Python
recipe 580790
by <a href="/recipes/users/4187447/">Ryan Gonzalez</a>
(<a href="/recipes/tags/annotations/">annotations</a>, <a href="/recipes/tags/class/">class</a>, <a href="/recipes/tags/self/">self</a>, <a href="/recipes/tags/type/">type</a>).
Revision 2.
</p>
<p>TL;DR: Short way of doing stuff like <code>def __init__(self, a, b): self.a = a; self.b = b</code>, using type annotations from PEP 484, inspired by Dart's <code>MyConstructor(this.a, this.b)</code> and Ruby's/Crystal's/(Moon|Coffee)Script's <code>constructor/initialize(@a, @b)</code>.</p>
Find the arity of a Python function (Python)
2017-01-30T14:09:47-08:00Vasudev Ramhttp://code.activestate.com/recipes/users/4173351/http://code.activestate.com/recipes/580753-find-the-arity-of-a-python-function/
<p style="color: grey">
Python
recipe 580753
by <a href="/recipes/users/4173351/">Vasudev Ram</a>
(<a href="/recipes/tags/functions/">functions</a>, <a href="/recipes/tags/introspection/">introspection</a>, <a href="/recipes/tags/python/">python</a>, <a href="/recipes/tags/python2/">python2</a>, <a href="/recipes/tags/reflection/">reflection</a>).
</p>
<p>This recipe shows how to find the arity of a given Python function. The arity of a function is the number of arguments the function takes. The recipe uses the inspect module of Python.</p>
<p>More details and sample output (including some limitations) here:</p>
<p><a href="https://jugad2.blogspot.in/2017/01/finding-arity-of-python-function.html" rel="nofollow">https://jugad2.blogspot.in/2017/01/finding-arity-of-python-function.html</a></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>
Python: Determine Name and Directory of the Top Level Running Script (Python)
2015-02-03T01:37:09-08:00Harald Liederhttp://code.activestate.com/recipes/users/4191581/http://code.activestate.com/recipes/579018-python-determine-name-and-directory-of-the-top-lev/
<p style="color: grey">
Python
recipe 579018
by <a href="/recipes/users/4191581/">Harald Lieder</a>
.
</p>
<p>Yet another way to provide this information.
I wanted to get the right answers in ANY situation: Python 2 or 3, compiled or interpreted (interactive or batch).
The following code has been tested under Windows, Python 2.7, Python 3.4, IDLE, IPython (sh and Qt), PyInstaller, cx_Freeze, py2exe.</p>
Keyword-only arguments in Python 2.x (Python)
2015-09-22T18:16:40-07:00Carahttp://code.activestate.com/recipes/users/4191397/http://code.activestate.com/recipes/578993-keyword-only-arguments-in-python-2x/
<p style="color: grey">
Python
recipe 578993
by <a href="/recipes/users/4191397/">Cara</a>
(<a href="/recipes/tags/arguments/">arguments</a>, <a href="/recipes/tags/decorator/">decorator</a>, <a href="/recipes/tags/keyword/">keyword</a>, <a href="/recipes/tags/keyword_only/">keyword_only</a>).
Revision 10.
</p>
<p>This is a decorator that makes some of a function's or method's arguments into keyword-only arguments. As much as it possible, it emulates the Python 3 handling of keyword-only arguments, including messages for TypeErrors. It's compatible with Python 3 so it can be used in code bases that support both versions.</p>
Python 2 nonlocal (Python)
2015-09-08T01:27:04-07:00Ryan Gonzalezhttp://code.activestate.com/recipes/users/4187447/http://code.activestate.com/recipes/578965-python-2-nonlocal/
<p style="color: grey">
Python
recipe 578965
by <a href="/recipes/users/4187447/">Ryan Gonzalez</a>
(<a href="/recipes/tags/backport/">backport</a>, <a href="/recipes/tags/nonlocal/">nonlocal</a>, <a href="/recipes/tags/python2/">python2</a>).
Revision 2.
</p>
<p>This implements nonlocal in Python 2...albeit in a slightly ugly way. Tested with CPython 2.7 and PyPy.</p>
Easy attribute setting and pretty representation (Python)
2014-12-03T09:55:06-08:00Joakim Petterssonhttp://code.activestate.com/recipes/users/4174760/http://code.activestate.com/recipes/578973-easy-attribute-setting-and-pretty-representation/
<p style="color: grey">
Python
recipe 578973
by <a href="/recipes/users/4174760/">Joakim Pettersson</a>
(<a href="/recipes/tags/attributes/">attributes</a>, <a href="/recipes/tags/lazy/">lazy</a>, <a href="/recipes/tags/traits/">traits</a>).
Revision 2.
</p>
<p>Mix in one or more of these classes to avoid those tedious lines of administrative code for setting attributes and getting useful representations. </p>
<p>If you inherit HasInitableAttributes, your should be able to obj = eval(repr(obj)) without loosing data.</p>
<p>enthought.traits.api.HasTraits seems to mix in well also.</p>
NondurableLogger class for use with concurrent.futures.ProcessPoolExecutor's submit and map methods (Python)
2014-02-10T17:50:59-08:00Peter Santorohttp://code.activestate.com/recipes/users/4189027/http://code.activestate.com/recipes/578827-nondurablelogger-class-for-use-with-concurrentfutu/
<p style="color: grey">
Python
recipe 578827
by <a href="/recipes/users/4189027/">Peter Santoro</a>
(<a href="/recipes/tags/logging/">logging</a>, <a href="/recipes/tags/multiprocessing/">multiprocessing</a>).
Revision 2.
</p>
<p>I needed a simple logging solution that I could use with with concurrent.futures.ProcessPoolExecutor and this is my initial recipe.</p>
More strict unittests using a validator (Python)
2014-03-01T12:37:47-08:00Thomas Lehmannhttp://code.activestate.com/recipes/users/4174477/http://code.activestate.com/recipes/578793-more-strict-unittests-using-a-validator/
<p style="color: grey">
Python
recipe 578793
by <a href="/recipes/users/4174477/">Thomas Lehmann</a>
(<a href="/recipes/tags/decorator/">decorator</a>, <a href="/recipes/tags/unittests/">unittests</a>, <a href="/recipes/tags/validator/">validator</a>).
Revision 4.
</p>
<p>The main point is that <strong>there was no binding between a unit tests and the concrete class</strong>. It did happend often that you are indirectly testing a class using it also the concrete test class has missed some concrete test methods. I found this fact sometimes very irritating seeing 100% coverage.</p>
<p>Therefor I now provide this class decorator where you can specify the class that will be tested. If you do not specify test methods for each method of the testable class <strong>an exception will be thrown providing a list of missed tests</strong>.</p>
<p>Here some examples how it works: You implemented a</p>
<ul>
<li>method "__eq__", then write a "testEqual" method</li>
<li>method "__init__", then write a testInit" method</li>
<li>method "scalar_product", then write a testScalarProduct" method</li>
<li>and so on ...</li>
</ul>
<p>The way to use this class decorator you can see in the doctest area (see below in the code)
The only point to be aware of is that when you use the decorator you have to implement all test to get rid of the thrown execption. Of course you can implement more tests for same class.</p>
<p>New in revision 4 (1st march 2014):</p>
<ul>
<li>Bugfix: the algorithm were not correctly detecting which methods were really overwritten forcing to implement tests for methods which were base class only.</li>
<li>Bugfix: decorated classes which contain the attribute "decorated_object" can be handled properly. </li>
<li><p>A new second parameter now allows you to implement several classes in same test class forcing you to include the class name in the test method:</p>
<ul>
<li>@ValidateTestResponsibilityFor(Square, True)</li>
<li>@ValidateTestResponsibilityFor(Sin, True)</li>
<li>=> testSquareInit, testSquareGet, testSinInit, testSinGet, ...</li>
<li>This for smaller classes to avoid too many files (at least ... you decided)</li>
</ul></li>
</ul>
Caller and Callee (Python)
2013-03-07T08:37:32-08:00Deepakhttp://code.activestate.com/recipes/users/4183429/http://code.activestate.com/recipes/578483-caller-and-callee/
<p style="color: grey">
Python
recipe 578483
by <a href="/recipes/users/4183429/">Deepak</a>
(<a href="/recipes/tags/callee/">callee</a>, <a href="/recipes/tags/caller/">caller</a>, <a href="/recipes/tags/debugging/">debugging</a>).
</p>
<p>A recipe to find out which function is the caller of the current function. </p>
<p>The <code>caller</code> function can be helpful for debugging — if there is no real debugger available. In terms of software engineering (loose coupling etc.) this should not be used in production code though.</p>
Evaluates string embedded expressions (rubstr module) (v 0.91) (Python)
2013-03-09T12:22:00-08:00SnarkTurnehttp://code.activestate.com/recipes/users/4185559/http://code.activestate.com/recipes/578487-evaluates-string-embedded-expressions-rubstr-modul/
<p style="color: grey">
Python
recipe 578487
by <a href="/recipes/users/4185559/">SnarkTurne</a>
.
Revision 2.
</p>
<p>This recipe allow you to write :</p>
<pre class="prettyprint"><code>>>> a,b=5,6
>>> rstr("If you add #{a} and #{b}, you'll get #{a+b}.")
If you add 5 and 6, you'll get 11.
</code></pre>
<p>This is more readble, from my point of view, than :</p>
<pre class="prettyprint"><code>"If you add {} and {}, you'll get {}.".format(a,b,a+b)
</code></pre>
<p>This recipe is inspired from the way Ruby evaluates strings :</p>
<pre class="prettyprint"><code>irb> a,b=5,6
irb> "If you add #{a} and #{b}, you'll get #{a+b}."
==> If you add 5 and 6, you'll get 11.
</code></pre>
Get full caller name (package.module.function) (Python)
2012-11-30T21:54:46-08:00anatoly techtonikhttp://code.activestate.com/recipes/users/4168147/http://code.activestate.com/recipes/578352-get-full-caller-name-packagemodulefunction/
<p style="color: grey">
Python
recipe 578352
by <a href="/recipes/users/4168147/">anatoly techtonik</a>
(<a href="/recipes/tags/caller/">caller</a>, <a href="/recipes/tags/debug/">debug</a>, <a href="/recipes/tags/logging/">logging</a>).
</p>
<p>This function allows to get fully qualified name of the calling function. I expected this field to be available from logging module, but it is not here <a href="http://docs.python.org/2/library/logging.html#logrecord-attributes" rel="nofollow">http://docs.python.org/2/library/logging.html#logrecord-attributes</a> It might be that it is too expensive for performance or just doesn't play well in some situations. I don't know. I use it solely when debugging and it is convenient.</p>
<p>Also here: <a href="https://gist.github.com/2151727" rel="nofollow">https://gist.github.com/2151727</a></p>
A Class Decorator that Adds a copy() Method (Python)
2013-02-14T20:43:20-08:00Eric Snowhttp://code.activestate.com/recipes/users/4177816/http://code.activestate.com/recipes/578457-a-class-decorator-that-adds-a-copy-method/
<p style="color: grey">
Python
recipe 578457
by <a href="/recipes/users/4177816/">Eric Snow</a>
(<a href="/recipes/tags/metaprogramming/">metaprogramming</a>).
</p>
<p>Here's a class decorator that adds a rudimentary copy() method onto the decorated class. Use it like this:</p>
<pre class="prettyprint"><code>@copiable
class SomethingDifferent:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
</code></pre>
<p>or like this:</p>
<pre class="prettyprint"><code>@copiable("a b c")
class SomethingDifferent:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
s = SomethingDifferent(1,2,3)
sc = s.copy()
assert vars(s) == vars(sc)
</code></pre>
<p>(Python 3.3)</p>
Peek at Python value stack (Python)
2013-01-08T22:15:21-08:00Dima Tisnekhttp://code.activestate.com/recipes/users/4068698/http://code.activestate.com/recipes/578412-peek-at-python-value-stack/
<p style="color: grey">
Python
recipe 578412
by <a href="/recipes/users/4068698/">Dima Tisnek</a>
(<a href="/recipes/tags/python/">python</a>, <a href="/recipes/tags/python2/">python2</a>, <a href="/recipes/tags/stack/">stack</a>).
</p>
<p>Poking at value stack, a.k.a. evaluation stack is not allowed in Python, however everything is doable with ctypes.</p>
<p>I think this could be useful in debugging complex statements.</p>
Code to source and back (Python)
2012-12-01T08:59:49-08:00Oren Tiroshhttp://code.activestate.com/recipes/users/2033964/http://code.activestate.com/recipes/578353-code-to-source-and-back/
<p style="color: grey">
Python
recipe 578353
by <a href="/recipes/users/2033964/">Oren Tirosh</a>
(<a href="/recipes/tags/ast/">ast</a>, <a href="/recipes/tags/decompile/">decompile</a>, <a href="/recipes/tags/recompile/">recompile</a>, <a href="/recipes/tags/uncompile/">uncompile</a>).
</p>
<p>Converts a code object to a source code snippet and back: <code>c == recompile(*uncompile(c))</code></p>
<p>This is useful, for example, if you want to apply an AST transformation to the code.</p>
Print an object only a limited number of times (Python)
2012-12-09T19:41:20-08:00Filippo Squillacehttp://code.activestate.com/recipes/users/4174931/http://code.activestate.com/recipes/578374-print-an-object-only-a-limited-number-of-times/
<p style="color: grey">
Python
recipe 578374
by <a href="/recipes/users/4174931/">Filippo Squillace</a>
.
</p>
<p>The psome function detects the position into the source files where the
function itself is called. It prints the object according a counter variable.
Therefore, whenever the psome function is called inside a loop the object will
be printed only a limited number of times. This can useful for debugging
code in particular when the data structure we want to scan is quite big and we
want to print only the first elements of it.</p>
Sequence Builder (Python)
2012-03-03T17:50:03-08:00Thomas Lehmannhttp://code.activestate.com/recipes/users/4174477/http://code.activestate.com/recipes/578061-sequence-builder/
<p style="color: grey">
Python
recipe 578061
by <a href="/recipes/users/4174477/">Thomas Lehmann</a>
(<a href="/recipes/tags/builder/">builder</a>, <a href="/recipes/tags/sequence/">sequence</a>).
Revision 2.
</p>
<p><strong>Why?</strong></p>
<ul>
<li>Thinking about a sequence of odd numbers where numbers divisible by 3 are not part of it I came to a sequence starting with 5, 7, 11, 13, 17, 19, ...</li>
<li>The interesting property of this sequence is that the sequence of differences between the individual elements are 2,4,2,4,2,...</li>
</ul>
<p><strong>How?</strong></p>
<ul>
<li>I'm not a math expert (unfortunately) but I could imagine that there is a quite simple formula to get this.</li>
<li>However I thought that using different combinations of defined functions a script could do the favour for me.</li>
</ul>
<p><strong>Result?</strong></p>
<ul>
<li>Formula: <code>(((-1)**(x-1))+1)+2</code> -> Simplified -> <code>-1**(x-1) + 3</code> (now clear to you?)</li>
<li>You have to look for the sequence [4, 2, 4, 2, 4, 2, 4, 2, 4, 2, 4, 2, 4, 2, 4, 2, 4, 2, 4, 2]</li>
</ul>
<p><strong>Out of scope:</strong></p>
<ul>
<li>Does not check for using lambda functions only and "x" only in the lambda functions.</li>
<li>The Python script does not simplify functions like changing ((x+1)+1) to x+2 - would be an interesting recipe - by the way :)</li>
</ul>
<p><strong>Please note</strong></p>
<ul>
<li>You should not add other functions than lambda.</li>
<li>You should always use "x" in your formular.</li>
<li>Be aware that the actual setup runs a few minutes (about 3 minutes) and you can imagine - surely - that adding further functions will definitely increase the runtime.</li>
</ul>
<p><strong>Side effects?</strong></p>
<ul>
<li>Quite funny to produce a sequence of nines with <code>(((-1)**(2*x))+2)**2</code>.</li>
<li>If you apply the first binomial theorem (a+b)^2 = a^2 + 2ab + b^2 then you see why!</li>
</ul>
<p><strong>What I have learned from this?</strong></p>
<ul>
<li>The biggest nightmare I did have with the Sequence class because of not knowing how to generate unique elements of this in a set (__eq__ and __hash__ are required); and I have to ensure that the hash code is calculated once only.</li>
<li>The 'combineFunctions' was interesting to me. I have never used 'inspect.getsource' before.</li>
<li>A few minutes does not sound much but for developing all times with more than 30 seconds are not comfortable. There are just 325 sequences and to investigate for certain sequences you probably have to have some more formula. Maybe I would have to take another approach for that.</li>
</ul>
Bunch class created from attributes in class (Python)
2011-12-31T18:03:02-08:00Fabio Zadroznyhttp://code.activestate.com/recipes/users/4180406/http://code.activestate.com/recipes/577999-bunch-class-created-from-attributes-in-class/
<p style="color: grey">
Python
recipe 577999
by <a href="/recipes/users/4180406/">Fabio Zadrozny</a>
(<a href="/recipes/tags/attributes/">attributes</a>, <a href="/recipes/tags/bunch/">bunch</a>, <a href="/recipes/tags/metaclass/">metaclass</a>).
Revision 3.
</p>
<p>Provide a way to construct class __init__, __slots__, __eq__, __ne__, __repr__ for the class and makes explicit which attributes each instance will have (and providing defaults).</p>
<p>The __main__ session shows an example of how it should be used.</p>
Simple enum mechanism (Python)
2012-01-15T12:30:31-08:00Thomas Lehmannhttp://code.activestate.com/recipes/users/4174477/http://code.activestate.com/recipes/578015-simple-enum-mechanism/
<p style="color: grey">
Python
recipe 578015
by <a href="/recipes/users/4174477/">Thomas Lehmann</a>
(<a href="/recipes/tags/enum/">enum</a>).
</p>
<p><strong>Here are the basic ideas (orientation: C++)</strong>:</p>
<ul>
<li>You are responsible to find names for constants and this code provides a way to give values which differ from each other</li>
<li>The context is to allow different enums with values starting by 0</li>
<li>If you like to use constants like here: "Orientation.TOP" then place those constants in the relating class</li>
<li>You still can assign your own values</li>
</ul>
<p><strong>About the code</strong>:</p>
<ul>
<li>It's not much code also it might look like (implementation + documentation + unittests)</li>
<li>The __docformat__ is for epydoc. Temporarily remove the "@singleton" when trying to generate the HTML documentation (can not yet be handled by epydoc).</li>
</ul>
<p><strong>Example(s)</strong>:
Have a look at the unittests please.</p>
Improved Signals/Slots implementation in Python (Python)
2011-12-12T22:47:25-08:00Christopher S. Casehttp://code.activestate.com/recipes/users/4180238/http://code.activestate.com/recipes/577980-improved-signalsslots-implementation-in-python/
<p style="color: grey">
Python
recipe 577980
by <a href="/recipes/users/4180238/">Christopher S. Case</a>
(<a href="/recipes/tags/events/">events</a>, <a href="/recipes/tags/qt4/">qt4</a>, <a href="/recipes/tags/signal/">signal</a>, <a href="/recipes/tags/slot/">slot</a>).
</p>
<p>I've modified the excellent <a href="http://code.activestate.com/recipes/576477-yet-another-signalslot-implementation-in-python/"><a href="http://code.activestate.com/recipes/576477/">recipe 576477</a></a> to allow for non method functions as well as method functions. This implementation also uses a WeakKeyDictionary instead of a WeakValueDictionary for reasons of code simplification/style.</p>