Embedding: How to set globals for PyObject_Call

Scott Gilbert xscottgjunk at yahoo.com
Thu Feb 21 17:41:09 CET 2002


"Jason Orendorff" <jason at jorendorff.com> wrote:
> Scott Gilbert wrote:
> > I dove through the code, and it appears that I need to setup a
> > PyFrameObject to be associated with my PyThreadState.  I wasn't able
> > to figure out how to do that though.
> > 
> > As you can see in my example below, I have the globals sitting right
> > there.  I just don't know how to tell Python that those are the
> > appropriate globals while invoking PyObject_Call(...).  A similar
> > problem occurs when evaluating "globals", "locals", "dir", or
> > functions that call those.
> 
> Really?  The part about "functions that call those" sounds a bit off.
> I thought Python functions that call globals() would work.
> Each Python function contains a pointer to its globals namespace
> (the fn.func_globals attribute), and calling a Python function
> creates a PyFrameObject.  It seems as though it should work.
> 

You're right, it's not a problem with functions that call those.  My
bad, I should have tried before making that assumption.  So I guess
it's not really that big of a problem.  Thank you for pointing this
out.

> So, what are you really trying to do?  :)  I have a feeling that
> calling vars() directly from C is a mistake; there's probably an
> easier way to do what you need.

I have a C++ object class "Var" (short for arbitrary Python Variable)
that represents a PyObject.  Var also has a ton of overloads
(including operator ()) to make it fairly transparent to work with. 
Here are three examples:

  // This one breaks
  Var g = VarEval("globals");
  g(); // This causes a segfault

  // This one works
  Var g = VarEval("globals()");

  // As you pointed out, This one works too
  VarExec("def GLOBALS(): return globals()");
  Var g = VarEval("GLOBALS");
  g();

Many other functions in the __builtin__ module work just fine.  For
instance:

  Var hex = VarEval("hex");
  VarPrint(hex(1234));

So I think it's a little odd that some builtins are different in this
regard than others.

> 
> For example, if you just want to look at module's namespace,
> that's easy:
> 
>   result = PyModule_GetDict(module);
> 

Actually, what I want is to allow the users of my library to do
anything from C++ that they could do from Python.  I know this isn't
possible completely, but I'm trying to fill in the edges where I can. 
The builtin functions "dir", "vars", "globals", "locals" will have to
go on the list of things that have quirks...

Thanks again for your response.



More information about the Python-list mailing list