Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This is almost certainly a bad idea… but it is doable, in a few different ways.</p> <hr> <p>Most simply, you can just have each function save its name in the object, e.g.:</p> <pre><code>def stash_name(func): @functools.wraps(func) def wrapper(self, *args, **kwargs): self._stashed_name = func.__name__ return func(self, *args, **kwargs) return wrapper class Test(object): @stash_name def foo(self, x): print x @stash_name def bar(self): print </code></pre> <p>Now, after calling <code>d.connect()</code>, <code>d._stashed_name</code> will be <code>"connect"</code>.</p> <hr> <p>At the opposite extreme, if you want to get really hacky, you can do this without any cooperation from the preceding method. Just use <code>sys._getframe(1)</code> to find your calling context, then you can examine the frame's <code>f_code</code> to see how you were called.</p> <p>You can use the <code>dis</code> module to see real bytecode. But basically, it will looks like this pseudo-bytecode:</p> <pre><code>LOAD_NAME d LOAD_ATTR connect &lt;possibly other ops to prepare arguments&gt; CALL_FUNCTION 1 (or any other CALL_FUNCTION_* variant) LOAD_ATTR setAttributes &lt;various other ops to prepare arguments&gt; CALL_FUNCTION 0 </code></pre> <p>In this case, you can either get the attribute name from the <code>LOAD_ATTR</code>, or get the <em>value</em> that was pushed and look at its <code>im_func.__name__</code>, depending which one you want.</p> <p>Of course there will be other cases that don't look like this. For example, let's say I called it as <code>getattr(d, ''.join('con', 'next'))()</code> instead of <code>d.connect()</code>. Or I looked up the unbound method and built a bound method on the fly. Or… What would you want to do in each such case? If you have the answers to all such cases, then you can work out the rule that generates those answers, then figure out how to get that from the bytecode.</p>
    singulars
    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.
    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