Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to access globals from a different point in code
    primarykey
    data
    text
    <p>I'm trying to find a way of basically doing a late <code>eval</code>, using context from a different location in the code. As an example, I have a class <code>Friend</code>, and it can be used like this:</p> <pre><code>&gt;&gt;&gt; class A: ... friend = Friend('B') ... &gt;&gt;&gt; class B: ... friend = Friend('A') ... &gt;&gt;&gt; A.friend.getobject() &lt;class '__main__.B'&gt; </code></pre> <p>However, <code>Friend</code> is defined elsewhere in the code, in a separate library, and would look something like this:</p> <pre><code>class Friend: def __init__(self, objname): self.objname = objname def getobject(self): return eval(self.objname, original_context) </code></pre> <p>The sqlalchemy ORM has a similar pattern for defining columns, but they implement it by tracking all owning classes (i.e. tables) in a session. I could do something similar if I need to, but I'd like to know if there is another way to do this. I've been looking at frames and the interpreter stack, and I think I can get to the relevant frame's locals using something like <code>inspect.stack()[1][0].f_locals</code>, but I would have to do this in <code>Frame.__init__</code> which is called before the object is defined.</p> <p>My questions is how to find <code>original_context</code>, but only at the time it is needed. This comes down to two issues: 1. How to access the environment (or frame?) in which <code>Friend</code> was instantiated. 2. How to access it at the time <code>getobject</code> is called.</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.
 

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