Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <blockquote> <p>Unfortunately, decorators (to my understanding), are interpreted when the function is defined. Hence it won't have access to instance's value. Is there a way to pass in dynamic data or values from the sub class?</p> </blockquote> <p>The template needs to be called with the <em>name</em> of the relevant attribute; the wrapper can then get that attribute's <em>value</em> dynamically. For example:</p> <pre><code>import functools def expose(attname=None): if attname: def makewrapper(f): @functools.wraps(f) def wrapper(self, *a, **k): attvalue = getattr(self, attname, None) ...use attvalue as needed... return wrapper return makewrapper else: ...same but without the getattr... </code></pre> <p>Note that the complication is only because, judging from the code snippets in your Q, you want to allow the <code>expose</code> decorator to be used both with and without an argument (you could move the <code>if attname</code> guard to live within <code>wrapper</code>, but then you'd uselessly repeat the check at each call -- the code within wrapper may also need to be pretty different in the two cases, I imagine -- so, shoehorning two different control flows into one wrapper may be even more complicated). BTW, this is a dubious design decision, IMHO. But, it's quite separate from your actual Q about "dynamic data".</p> <p>The point is, by using the attribute name as the argument, you empower your decorator to fetch the value dynamically "just in time" when it's needed. Think of it as "an extra level of indirection", that well-known panacea for all difficulties in programming!-)</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload