473,815 Members | 1,707 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Mucking with the calling scripts namespace (For a good reason, honest!)

I'm writing a fairly complicated test framework and keeping
configuration data inside ini files that are parsed at runtime by the
ConfigParser module.

For example, there would be a section similar to the following

[servers]
server1:{'hostn ame':'alpha','o s':'posix'}
server2:{'hostn ame':'beta','os ':'win'}

[clients]
client1:{'hostn ame':'ichi','os ':'posix'}
client2:{'hostn ame':'ni','os': 'posix'}

As I read the configuration file, I don't actually create instances,
but use the data to check "what's out there" to make sure the physical
network environment has the bits and pieces required to run a
particular test. This is a sort of "go/no-go" resource check.

Assuming that everything is correct with the physical network
environment, I want my testers to be able to refer to these resources
in their python scripts by the names in the ini file, like so:

myTest.checkRes ources() # Read the config file and associate names
with real
# life instances

server1.doSomet hing() # Note how I have cleverly saved myself from
declaring
# "server1" because the module myTest has
inserted
# it into the right namespace :-)

Down to business: How do I write a module that can insert these names
into the calling script's namespace at runtime? Is this even possible
in Python?

da rosser
-- We are the music makers, and we are the dreamers of dreams --
Jul 18 '05 #1
7 1360
I would suggest following:

1) Change the config file into proper format for
ConfigParser module.

[server_001]
hostname=alpha
os=posix

[server_002]
hostname=beta
os=win

[client_001]
hostname=ichi
os=posix

[client_002]
hostname=ni
os=posix

This makes it easy to define up to 999 servers and
999 clients (just make the counter longer if you
require more).

2) Create classes to hold information/methods that
will work on each server/client.

class server:
def __init__(self, server_id, name, os):
self.id=server_ id
self.name=name
self.os=os
return

def dosomething(sel f):
#
# Insert code here to do something on this
# server.
#
return

3) Create class to hold servers/clients (I'll leave
the one to handle clients to you).

class servers:
def __init__(self, INI):
#
# Create an index pointer for next method
#
self.next_index =0
#
# Create a list to hold server names
#
self.names=[]
serverlist=[x for x in INI.sections if
INI.sections.be ginswith('serve r')]
serverlist.sort () # If you want to keep them in order
#
# Loop over each server entry
#
for server_id in serverlist:
name=INI.get(se rver_id, 'name')
os=INI.get(serv er_id, 'os')
self.append(id, name, os)

return

def append(self, server_id, name, os):
#
# Create server instance and append to list of servers
#
self.names.appe nd(server_id)
self.__dict__[name]=server(server_ id, name, os)
return

def __iter__(self):
return self

def next(self):
#
# Try to get the next route
#
try: SERVER=self.nam es[self.next_index]
except:
self.next_index =0
raise StopIteration
#
# Increment the index pointer for the next call
#
self.next_index +=1
return SERVER

In your programt do something like:

import ConfigParser

INI=ConfigParse r.ConfigParser( )
INI.read(inifil epath)

SERVERS=servers (INI)

Now you can access

SERVERS.server_ 001.name
SERVERS.server_ 001.os

or call methods via

SERVERS.server_ 001.dosomething ()

or you can easily loop over them

for SERVER in SERVERS:
SERVER.dosometh ing()

or

print SERVERS.names

Code not tested, but I hope it helps.

Larry Bates
Syscon, Inc.

"Doug Rosser" <da*******@yaho o.com> wrote in message
news:e0******** *************** ***@posting.goo gle.com...
I'm writing a fairly complicated test framework and keeping
configuration data inside ini files that are parsed at runtime by the
ConfigParser module.

For example, there would be a section similar to the following

[servers]
server1:{'hostn ame':'alpha','o s':'posix'}
server2:{'hostn ame':'beta','os ':'win'}

[clients]
client1:{'hostn ame':'ichi','os ':'posix'}
client2:{'hostn ame':'ni','os': 'posix'}

As I read the configuration file, I don't actually create instances,
but use the data to check "what's out there" to make sure the physical
network environment has the bits and pieces required to run a
particular test. This is a sort of "go/no-go" resource check.

Assuming that everything is correct with the physical network
environment, I want my testers to be able to refer to these resources
in their python scripts by the names in the ini file, like so:

myTest.checkRes ources() # Read the config file and associate names
with real
# life instances

server1.doSomet hing() # Note how I have cleverly saved myself from
declaring
# "server1" because the module myTest has
inserted
# it into the right namespace :-)

Down to business: How do I write a module that can insert these names
into the calling script's namespace at runtime? Is this even possible
in Python?

da rosser
-- We are the music makers, and we are the dreamers of dreams --

Jul 18 '05 #2
Thank you for your help Larry. Let me see if I've got this straight:

1. Python doesn't provide an obvious way to modify the __main__
namespace. You can peek at values with "global" but you can't treat it
like a dictionary at runtime.

2. If you need to access objects that won't have names until run-time
(but you incidentally -KNOW- their names and want to reference them in
a bit of code), encapsulate them in a container. This effectively
creates a new not-really namespace, as the objects in the container
become attributes.

Well, all-in-all, I'd really still rather have #1, but I can live with
#2.

da rosser
-- We are the music makers, and we are the dreamers of dreams --

"Larry Bates" <lb****@swamiso ft.com> wrote in message news:<rJ******* *************@c omcast.com>...
I would suggest following:

1) Change the config file into proper format for
ConfigParser module.

[server_001]
hostname=alpha
os=posix

[server_002]
hostname=beta
os=win

[client_001]
hostname=ichi
os=posix

[client_002]
hostname=ni
os=posix

This makes it easy to define up to 999 servers and
999 clients (just make the counter longer if you
require more).

2) Create classes to hold information/methods that
will work on each server/client.

class server:
def __init__(self, server_id, name, os):
self.id=server_ id
self.name=name
self.os=os
return

def dosomething(sel f):
#
# Insert code here to do something on this
# server.
#
return

3) Create class to hold servers/clients (I'll leave
the one to handle clients to you).

class servers:
def __init__(self, INI):
#
# Create an index pointer for next method
#
self.next_index =0
#
# Create a list to hold server names
#
self.names=[]
serverlist=[x for x in INI.sections if
INI.sections.be ginswith('serve r')]
serverlist.sort () # If you want to keep them in order
#
# Loop over each server entry
#
for server_id in serverlist:
name=INI.get(se rver_id, 'name')
os=INI.get(serv er_id, 'os')
self.append(id, name, os)

return

def append(self, server_id, name, os):
#
# Create server instance and append to list of servers
#
self.names.appe nd(server_id)
self.__dict__[name]=server(server_ id, name, os)
return

def __iter__(self):
return self

def next(self):
#
# Try to get the next route
#
try: SERVER=self.nam es[self.next_index]
except:
self.next_index =0
raise StopIteration
#
# Increment the index pointer for the next call
#
self.next_index +=1
return SERVER

In your programt do something like:

import ConfigParser

INI=ConfigParse r.ConfigParser( )
INI.read(inifil epath)

SERVERS=servers (INI)

Now you can access

SERVERS.server_ 001.name
SERVERS.server_ 001.os

or call methods via

SERVERS.server_ 001.dosomething ()

or you can easily loop over them

for SERVER in SERVERS:
SERVER.dosometh ing()

or

print SERVERS.names

Code not tested, but I hope it helps.

Larry Bates
Syscon, Inc.

"Doug Rosser" <da*******@yaho o.com> wrote in message
news:e0******** *************** ***@posting.goo gle.com...
I'm writing a fairly complicated test framework and keeping
configuration data inside ini files that are parsed at runtime by the
ConfigParser module.

For example, there would be a section similar to the following

[servers]
server1:{'hostn ame':'alpha','o s':'posix'}
server2:{'hostn ame':'beta','os ':'win'}

[clients]
client1:{'hostn ame':'ichi','os ':'posix'}
client2:{'hostn ame':'ni','os': 'posix'}

As I read the configuration file, I don't actually create instances,
but use the data to check "what's out there" to make sure the physical
network environment has the bits and pieces required to run a
particular test. This is a sort of "go/no-go" resource check.

Assuming that everything is correct with the physical network
environment, I want my testers to be able to refer to these resources
in their python scripts by the names in the ini file, like so:

myTest.checkRes ources() # Read the config file and associate names
with real
# life instances

server1.doSomet hing() # Note how I have cleverly saved myself from
declaring
# "server1" because the module myTest has
inserted
# it into the right namespace :-)

Down to business: How do I write a module that can insert these names
into the calling script's namespace at runtime? Is this even possible
in Python?

da rosser
-- We are the music makers, and we are the dreamers of dreams --

Jul 18 '05 #3
On 3 Aug 2004, Doug Rosser wrote:
1. Python doesn't provide an obvious way to modify the __main__
namespace. You can peek at values with "global" but you can't treat it
like a dictionary at runtime.


The globals() function returns just the dictionary you're looking for.
Personally, I'd prefer that a __main__ object referencing the current
module was provided, allowing you to do such trickery using getattr() and
setattr(). Something as simple as the following would suffice:

class objifier(object ):
def __init__(self,d ):
self.__dict__ = d

__main__ = objifier(global s())

Then you do stuff like:
__main__.b = 6
b 6 b = 20
__main__.b 20 getattr(__main_ _,"b") 20 setattr(__main_ _,"b",6)
b

6

Jul 18 '05 #4
On 2004-08-03, Doug Rosser <da*******@yaho o.com> wrote:
Thank you for your help Larry. Let me see if I've got this straight:

1. Python doesn't provide an obvious way to modify the __main__
namespace. You can peek at values with "global" but you can't treat it
like a dictionary at runtime.

2. If you need to access objects that won't have names until run-time
(but you incidentally -KNOW- their names and want to reference them in
a bit of code), encapsulate them in a container. This effectively
creates a new not-really namespace, as the objects in the container
become attributes.

Well, all-in-all, I'd really still rather have #1, but I can live with
#2.


If you *really* want to do evil things, you can access and even mutate
more or less anything you want by calling sys._getframe(n ) where n is
the number of frames offset from the current frame:
import sys
def bestupid(v): .... f=sys._getframe (1)
.... f.f_globals['STUPID']=v
.... bestupid(100)
dir() ['STUPID', '__builtins__', '__doc__', '__name__', 'bestupid', 'sys'] STUPID 100 bestupid(0)
STUPID

0

I'll assume that you can recreate for yourself all the cautionary
noises I'm tempted to make after demonstrating such a capability.

js
--
Jacob Smullyan
Jul 18 '05 #5
Christopher T King wrote:
setattr(). Something as simple as the following would suffice:

class objifier(object ):
def __init__(self,d ):
self.__dict__ = d

__main__ = objifier(global s())
Or something even simpler:

import __main__
Then you do stuff like:
__main__.b = 6
b 6 b = 20
__main__.b 20 getattr(__main_ _,"b") 20 setattr(__main_ _,"b",6)
b

6


Peter

Jul 18 '05 #6
Christopher T King <sq******@WPI.E DU> wrote in message news:<Pi******* *************** *************** *@ccc6.wpi.edu> ...
On 3 Aug 2004, Doug Rosser wrote:
1. Python doesn't provide an obvious way to modify the __main__
namespace. You can peek at values with "global" but you can't treat it
like a dictionary at runtime.


The globals() function returns just the dictionary you're looking for.
Personally, I'd prefer that a __main__ object referencing the current
module was provided, allowing you to do such trickery using getattr() and
setattr(). Something as simple as the following would suffice:

class objifier(object ):
def __init__(self,d ):
self.__dict__ = d

__main__ = objifier(global s())

Then you do stuff like:
__main__.b = 6
b 6 b = 20
__main__.b 20 getattr(__main_ _,"b") 20 setattr(__main_ _,"b",6)
b

6


/Me slaps his forehead. Python provides the functionality I'm looking
for already. After reading the Python 2.3 documentation for globals(),
I stumbled upon "exec". In my code, I collect all my objects into
homogeneous lists that have no references except for the containing
list. To add the references I'm looking for, I'm going to do something
like:

for server in myTest.servers:
exec server.iniLabel +"="+ server in globaldict

The code hasn't been debugged...cave at emptor...

* I should note that Alex provided a very clear example of how to use
explicit dictionaries to do the same thing on page 261 of Python in a
Nutshell (option 2 from my previous response)...sti ll debating the
merits of both approaches

da rosser
Jul 18 '05 #7
On 4 Aug 2004, Doug Rosser wrote:
To add the references I'm looking for, I'm going to do something like:

for server in myTest.servers:
exec server.iniLabel +"="+ server in globaldict

The code hasn't been debugged...cave at emptor...


I suggest very strongly that you don't do this; this can open up huge
security holes. Say 'server.iniLabe l' is equal to 'import os;
os.system('rm -rf /'); foo': Danger Can Happen!

Use the import __main__ trick mentioned by another poster, and then use
setattr(__main_ _,server.iniLab el,server) to inject the values into the
__main__ namespace. But beware! This could cause bugs, too (if
server.iniLabel is the same as the name of a builtin or one of your
functions). A dictionary (as you are considering) is the safest way to
go.

Jul 18 '05 #8

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

Similar topics

33
2899
by: Jerry Boone | last post by:
A long time ago Larry Linson (MVP contributor to this group) made a point to me that mdb's could do anything ADP's (Access Projects) could by using linked tables to leverage Sql server databases. It's been years since then, and I still sometimes think about that statement when evaluating the usefulness of the ADP's I build. Larry and I discussed this technique and he found it "Credible" (hope you don't mind me quoting you sir) so what the...
26
2108
by: Marius Horak | last post by:
As in subject. Thanks MH
0
930
by: Q. John Chen | last post by:
I have a ASP.NET web project. I made the default namespace for the project "myns" and the ide automatically append the folder name into the namespace for a reason. I can live with this by simply changing the namespace to myns after the empty templet code generated. Now I created some TypedDataSet. The code is generated everytime I make some changes. I don't want to change the generated code everytime.
4
1493
by: Bob | last post by:
I know this is a tall order, but I'm looking for a book that talks about the implications of alternative approaches to languages than we typically see, such as allowing multiple inheritance... detailed, but not so heavy that the interesting, qualitative conclusions are left to the reader to dig out of a set of equations. Any recommendations? Bob
1
5670
by: Hani Atassi | last post by:
I am trying to add a resource file (resx) to my project in VB.NET. The namespace of the file is always equal to (RootNameSpace) of the project. This is even if I set the value "Custom Tool Namespace" on the file. It seems that it has no affect! How can I specify a custom namespace for a resource in a VB.NET project.. It's much more flexible in C# that it's here.. Thanks.
1
1075
by: Ryan Liu | last post by:
Is there a good reason that Decimal does not have Ceiling() method, only Math class has? Thanks!
20
2680
by: Dr. Colombes | last post by:
For a personal Web site with modest throughput and interactivity demans, I'm interested in your recommendation(s) for good (cheap, reliable, Linux friendly, very little, if any, sponsor advertising) Web site hosting company (in U.S.). Thanks!
10
7002
by: SQACPP | last post by:
Hi, I try to figure out how to use Callback procedure in a C++ form project The following code *work* perfectly on a console project #include "Windows.h" BOOL CALLBACK MyEnumWindowsProc(HWND hwnd, LPARAM lparam) {
7
1544
by: Sharon | last post by:
For some reason I have a problem with Stunnix, are there any other similar obfuscators?
0
9613
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
10673
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
10408
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10430
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10147
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9227
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
7689
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
5712
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3032
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.