A second __builtins__- or globals()-like namespace.

  • Thread starter Jacek Generowicz
  • Start date
J

Jacek Generowicz

Python looks up names firstly in the nested function namespaces, then
the global namespace, and finally in builtins, raising NameError if it
fails to find a binding in any of those.

Would it be possible (without hacking the interpreter) to add in
another namespace somewhere into this search hierarchy?






======================================================================

If you want more background ...


I have an application which generates Python proxies for C++ objects,
automatically. For example, given

namespace foo {
struct bar {
void zot();
};
}

the application automatically creates an object "foo" of type
Namespace, contaiting an attribute "bar" of type "Cclass", contaiting
an attribute "zot" of type "CMethod".

IOW, it's as if someone had written

class Namespace:
pass

class

So far, I am storing the whole C++ scope tree (rooted at C++' global
namespace) in a variable, say "g", which makes the user refer to the
aforementioned "zot" as "g.foo.bar.zot". I would like to get rid of
the leading "g." without polluting globals() or __builtins__ (and
providing a means of explicit disambiguation of any name
clashes). IOW, I would like an object (eg __cpp__), in which Python
tries to find the binding of a name after looking in globals() but
before looking in __builtins__ (or maybe after __builtins__, or even
before globals()).
 
D

Daniel Dittmar

Jacek said:
Python looks up names firstly in the nested function namespaces, then
the global namespace, and finally in builtins, raising NameError if it
fails to find a binding in any of those.

Would it be possible (without hacking the interpreter) to add in
another namespace somewhere into this search hierarchy?

You could try to replace the __builtins__ module with an object of your own
liking.

class IntermediateScope:
def __init__ (self, outerscope, **kwargs):
for name, value in kwargs.items ():
setattr (self, name, value)
self.outerscope = outerscope

def __getattr__ (self, name):
return getattr (self.outerscope, name)

sys.modules ['__builtins__'] = IntermediateScope (__builtins__, myvar =
myvalue)

I haven't tested whether this works at all and what the effect on error
messages could be.

Daniel
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Staff online

Members online

Forum statistics

Threads
473,767
Messages
2,569,571
Members
45,045
Latest member
DRCM

Latest Threads

Top