473,788 Members | 3,030 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Changing behaviour of namespaces

Hi!

This is in Python 2.3.4 under WinXP.

I have a situation where I think changing the behaviour of a namespace
would be very nice. The goal is to be able to run a python file from
another in a separate namespace in such a way that a NameError is not
raised if a non-existing variable is used in the file. The file that I
want to run is taken out of context, and some needed variables may be
missing that are normally there when used in the intended context. OK!
When I run it out of context, I do not want the execution to stop
half-way through the file based on NameErrors, instead a predefined
dummy variable should be used. The question is: Can I achieve that?

Google didn't give me much, so I experimented a bit: First, I created a
dummy object, which is meant to be used when a variable is missing:

class dummyClass(obje ct):
pass
dummyObject = dummyClass()

The actual dummy object is supposed to be a bit more complicated than
that. The next step was to subclass dict:

class forgivingDict(d ict):
def __init__(self,* args,**kwargs):
dict.__init__(s elf,*args,**kwa rgs)
def __getitem__(sel f,key):
print ' Getting', key
try:
return dict.__getitem_ _(self,key)
except KeyError:
return dummyObject
def __setitem__(sel f,key,value):
print ' Setting', key, 'to', value
dict.__setitem_ _(self,key,valu e)
def __contains__(se lf,item):
return True
def __repr__(self):
return 'forgivingDict( %s)' % (dict.__repr__( self),)

Then I tried to execute a file using a forgivingDict() as namespace:

ns = forgivingDict()
execfile(filePa th, ns)

A file containing the following passes perfectly OK:

a = 0
b = a

But a file containing the following produces a NameError:

b = a

The error traceback for the interested:

Traceback (most recent call last):
File "//charm/mikael/My
Documents/Programmering/Python/Tester/voidTest.py", line 130, in ?
execfile('test2 .py', ns)
File "test2.py", line 1, in ?
b = a
NameError: name 'a' is not defined

Now, that is exactly what is to expect if ns is a dict(), but I was
hoping that b would have ended up as dummyObject when ns is a
forgivingDict() . One thing: Nothing is printed out when execfile-ing the
files, which means that the methods forgivingDict._ _getitem__ and
forgivingDict._ _setitem__ are never used. My guess was that the
execution done by execfile uses dict.__getitem_ _(ns, key) and
dict.__setitem_ _(ns,key,value) instead of ns[key] and ns[key]=value when
getting and setting variables. That is probably intentional from the
developers and done that way for a good reason.

Alternative test: I've tried to replace __builtin__.dic t with my
forgivingDict, slightly modified to make sure that the inheritance still
works, which didn't change anything. So it seams that the execution done
by execfile does *not* use dict.__getitem_ _(ns, key) and
dict.__setitem_ _(ns,key,value) after all, but something else. Probably
the original dict is around somewhere else, and execfile uses the
corresponding methods of that.

My approach seems flawed. Any ideas? Can I somehow execute a complete
file even if there are non-existent variables used somewhere? A
try-except around the execfile statement is not an alternative, since
that stops the execution where the error occurs.

Should I perhaps read up on the compiler module? I mean: Using the
compiler module to analyze the content of the file, and based on that
updating my namespace before executing the file.

/MiO
Sep 21 '06 #1
4 1565
Mikael Olofsson wrote:
This is in Python 2.3.4 under WinXP.
To feed an arbitrary mapping object to execfile() you need to upgrade to
Python 2.4.

http://docs.python.org/dev/lib/built...cs.html#l2h-26

Peter
Sep 21 '06 #2
Peter Otten wrote:
To feed an arbitrary mapping object to execfile() you need to upgrade to
Python 2.4.
Thanks! As clear as possible. I will do that.

FYI: I think I managed to achieve what I want in Py2.3 using the
compiler module:

def getNamesFromAst Node(node,varSe t):
if node.__class__ in (compiler.ast.G lobal,compiler. ast.Import):
varSet.union_up date(node.names )
if node.__class__ in (compiler.ast.N ame,):
varSet.add(node .name)
for subNode in node.getChildNo des():
getNamesFromAst Node(subNode,va rSet)

# Get all variable names that are referenced in the file:
varSet = sets.Set()
mainNode = compiler.parseF ile(filePath)
getNamesFromAst Node(mainNode,v arSet)

# Define a namespace and update it:
ns = {}
for varName in varSet:
ns[varName] = dummyObject

# Execute the file without NameErrors:
execfile(filePa th,ns)

Batteries included!

/MiO
Sep 21 '06 #3
Mikael Olofsson wrote:
Peter Otten wrote:
>To feed an arbitrary mapping object to execfile() you need to upgrade to
Python 2.4.

Thanks! As clear as possible. I will do that.

FYI: I think I managed to achieve what I want in Py2.3 using the
compiler module:

def getNamesFromAst Node(node,varSe t):
if node.__class__ in (compiler.ast.G lobal,compiler. ast.Import):
varSet.union_up date(node.names )
if node.__class__ in (compiler.ast.N ame,):
varSet.add(node .name)
for subNode in node.getChildNo des():
getNamesFromAst Node(subNode,va rSet)

# Get all variable names that are referenced in the file:
varSet = sets.Set()
mainNode = compiler.parseF ile(filePath)
getNamesFromAst Node(mainNode,v arSet)

# Define a namespace and update it:
ns = {}
for varName in varSet:
ns[varName] = dummyObject

# Execute the file without NameErrors:
execfile(filePa th,ns)

Batteries included!
Clearly more elegant than:
>>print open(filename). read()
b = a
>>dummy = 42
names = []
while 1:
.... ns = dict((n, dummy) for n in names)
.... try:
.... execfile(filena me, ns)
.... except NameError, e:
.... names.append(e[0][6:-16])
.... else:
.... break
....
>>names
['a']

:-)

Peter
Sep 21 '06 #4
Peter Otten wrote:
Clearly more elegant than:

>>>print open(filename). read()
b = a
>>>dummy = 42
names = []
while 1:
... ns = dict((n, dummy) for n in names)
... try:
... execfile(filena me, ns)
... except NameError, e:
... names.append(e[0][6:-16])
... else:
... break
...
>>>names
['a']
That sure is nicer. My solution looks like shooting mosquitoes with an
elephant rifle i comparison. Thanks.

/MiO
Sep 21 '06 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

21
1895
by: Blue Ocean | last post by:
Forgive me for asking so many questions so quickly. I am simply asking as they come up unanswered in my book. Can you change namespaces half way through a file? For instance, if you want to use std and then half way through switch to your own: { ... using namespace std; cout << "doing polygons"; using namespace polygon;
3
1256
by: CHRISTOF WARLICH | last post by:
Hi, the following few lines of code are showing a quite strange and unexpected behaviour of namespaces that makes me worry wheater I should rely on namespaces in the future at all. The example below compiles if OK is defined, but gives the following error otherwise:
11
1793
by: Random | last post by:
I'm confused about the proper use and usefulness of namespaces. I beleive I understand the purpose is so the developer can put classes within namespaces to essentially organize your code. And I understand that you declare your intention to use a namespace within a page through the "Inherits" attribute. I know that using "Inherits" isn't absolutely necessary, it's just recommended so the developer doesn't have to type out the entire...
2
2470
by: junky_fellow | last post by:
guys, If I declare a const variable and then try to change it as follows; const int i=5; i = 10; What would be the behaviour? Should compiler give compilation error or Warning ? Or, would I get a run time error (some exception as I am trying to
0
9655
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9498
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10363
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8993
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7517
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6749
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5398
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4069
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2894
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.