473,769 Members | 7,558 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

dynamic creation of global Identifier

Hello alltogether,

I've a little problem in creating a new identifier in the global namespace. The
following code creates a as local var in the namespace of init()

class A:
def __init__(self, v):
print "ctr of", self.__class__, "with", v
self._v = v

def init():
newIdentifier = ["a", "b"]
param = [1,2]
for newId, par in zip(newIdentifi er, param):
exec "global %s" % newId
exec "%s = A(par)" % newId

init()
print a, b

but why doesent exec "global ... create a identifier in the global namespace.

The next thing I want to do is to create a identifier in a packages namespace
anyhow from where init() is called. How can I (or can I not) access from within
a function the namespace of the "package" where it is defined?

Thanks a lot
Alexander

Oct 11 '06 #1
2 1218
On 10/11/06, Alexander Eisenhuth <ne******@staco m-software.dewrot e:
but why doesent exec "global ... create a identifier in the global namespace.
I haven't had much use for exec, but it operates in its own, more or
less cloistered namespace. It can't set globals among other things.

You can frob the globals like so

import __builtin__
__builtin__.__d ict__['foo'] = 42

But by the time you get there, it is almost certainly time to refactor.

-- Theerasak
Oct 11 '06 #2
Theerasak Photha wrote:
On 10/11/06, Alexander Eisenhuth <ne******@staco m-software.dewrot e:

>>but why doesent exec "global ... create a identifier in the global namespace.


I haven't had much use for exec, but it operates in its own, more or
less cloistered namespace. It can't set globals among other things.
Well that's not strictly true:
>>globals()
{'__builtins__' : <module '__builtin__' (built-in)>, '__name__':
'__main__', '__file__': '/c/Steve/.pythonrc', 'sys': <module 'sys'
(built-in)>, '__doc__': None}
>>exec "NEW = 42"
globals()
{'__builtins__' : <module '__builtin__' (built-in)>, '__file__':
'/c/Steve/.pythonrc', 'sys': <module 'sys' (built-in)>, 'NEW': 42,
'__name__': '__main__', '__doc__': None}

The problem was that the two exec statements were being treated
separately because they use independent execution contexts. Make them
the same, and bingo!

sholden@bigboy ~/Projects/Python
$ cat test38.py
class A:
def __init__(self, v):
print "ctr of", self.__class__, "with", v
self._v = v

def init():
newIdentifier = ["a", "b"]
param = [1,2]
for newId, par in zip(newIdentifi er, param):
exec """\
global %s
%s = A(par)""" % (newId, newId)

init()
print a, b

sholden@bigboy ~/Projects/Python
$ python test38.py
ctr of __main__.A with 1
ctr of __main__.A with 2
<__main__.A instance at 0x186c6d2c<__ma in__.A instance at 0x186c6e0c>

However, none of this will necessarily get the OP further, since the
interpretation of the global statement will be as "global to the module
that it appears in".

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

Oct 11 '06 #3

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

Similar topics

8
2559
by: lawrence | last post by:
I'm learning Javascript. I downloaded a script for study. Please tell me how the variable "loop" can have scope in the first function when it is altered in the second function? It is not defined in global space, therefore it is not a global variable, yes? Even if it was global, how would it get from one function to another? In PHP variables are copied by value. Are they copied by reference in Javascript? <SCRIPT LANGUAGE="JavaScript">
60
10193
by: Peter Olcott | last post by:
I need to know how to get the solution mentioned below to work. The solution is from gbayles Jan 29 2001, 12:50 pm, link is provided below: > http://groups.google.com/group/comp.lang.c++/msg/db577c43260a5310?hl > >Another way is to create a one dimensional array and handle the >indexing yourself (index = row * row_size + col). This is readily >implemented in template classes that can create dynamically allocated >multi-dimensional...
44
3384
by: petermichaux | last post by:
Hi, I have been using the following line of code to create an object called "Serious" if it doesn't already exist. if (Serious == null) {var Serious = {};} This works in the scripts I use it but but www.jslint.com is not happy with me.
2
3452
by: Ron M. Newman | last post by:
Hi, Just need a little advice. Id like to build *dynamic* context menus for tree nodes. I'm pretty versed in building context menus and attaching them to tree nodes. My question is, what event to I "capture" in order to build the tree node menu in real time? right click on a tree node? or is it too late? just FYI: the menu is different for each node and is based on "real time"
4
5069
by: hobbes992 | last post by:
Howdy folks, I've been working on a c project, compiling using gcc, and I've reached a problem. The assignment requires creation of a two-level directory file system. No files have to be added or deleted, however it must be initialized by a function during run-time to contain so many users which each contain so many directories of which each contain so many files. I've completed the program and have it running flawlessly without implementing...
1
1591
by: dav3 | last post by:
Any help here is appreciated folks. First in my Person class the comments = errors visual basics is giving me and I am not sure why. Also when i try and set up my array of pointers to Student class I get the error that is in the comment. This is really bothering me as I spent the last hour and a half with a classmate working on this and we can not figure out whats up. class Person { public: Person(int sinNumber, char studentName);...
3
4295
by: meeko | last post by:
hi, i am trying to create a dynamic sql to compare the old and new values in a table by usind a procedure as follows The g_o_rec and g_n_rec are global variables declared at the package level When I execute this, it always goes into exeception with the following error sqlerrm ORA-00904: "G_N_REC"."PHONE": invalid identifier sqlerrm ORA-00904: "G_N_REC"."CONTACT_PHONE": invalid identifier sqlerrm ORA-00904: "G_N_REC"."WEBPAGE_URL":...
1
4915
by: cdmsenthil | last post by:
I have an Infragistics UltrawebGrid . Each Row in the grid is attached to a context menu using Infragistics CSOM Upon click on the menu, I am creating an Iframe dynamically which points to another page in the same domain which also contains infragistics datagid populated with default data retrieved from Data Base. After creating the frame I am attaching it to the HTML DOM and show it as modal popup with OK and Cancel Button inside an...
112
5475
by: istillshine | last post by:
When I control if I print messages, I usually use a global variable "int silent". When I set "-silent" flag in my command line parameters, I set silent = 1 in my main.c. I have many functions that may print some messages. foo(...) { if (!silent)
0
9589
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
10048
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...
0
9865
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
8872
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
7410
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
6674
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
5304
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
3963
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
2815
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.