automatically naming a global variable 
Author Message
 automatically naming a global variable

If I have a string variable defined, how can I create a global
variable with the same name as the string?

For example:

Quote:
>>> x = "variable_name'

Now I want to be able to use x to create a global variable whose
name is 'variable_name'


Sat, 08 Nov 2003 22:19:35 GMT  
 automatically naming a global variable


Quote:

> If I have a string variable defined, how can I create a global
> variable with the same name as the string?

> For example:

>>>> x = "variable_name'

> Now I want to be able to use x to create a global variable whose
> name is 'variable_name'

Have you stopped to consider that this may be a *bad* idea, and perhaps
there is a better way to achieve whatever you want to do? In particular
creating global variables when you don't know their names in advance is
likely to conflict with the names of other globals (modules, functions
etc.) that are essential to the running of your program.
Much better would be to create a dictionary to hold your unknown variables:

mydict = {}
mydict[x] = 'some value'

That way you keep all these values with unknown names together and well
clear of everything else.

If you still want to modify globals() indirectly, you can do it:
mydict = globals()
mydict[x] = 'some value'

Also don't forget that a global variable in python is a lot less global
than in most other languages (thank goodness).
--

int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?



Sat, 08 Nov 2003 23:21:43 GMT  
 automatically naming a global variable

Quote:

> If I have a string variable defined, how can I create a global
> variable with the same name as the string?

> For example:

> >>> x = "variable_name'

> Now I want to be able to use x to create a global variable whose
> name is 'variable_name'

setattr(sys.modules[__name__], x, 23) should work (if you
have imported sys, of course).  A global variable is no more
and no less than an attribute on your current module object,
after all.  sys.modules[__name__] is one way to say "the
module this code is in" (there are other ways).

But this is hardly ever appropriate.  Generally, on digging
a bit deeper, it turns out that whatever problem you think
you're solving is better solved otherwise -- generally by
more explicitly using a dictionary, as it happens (objects
taking arbitrarily-named attributes, such as modules for
example, implicitly use dictionaries, too).

Somebody is sure to suggest the exec statement... I suggest
you ignore the suggestion:-).

Alex



Sun, 09 Nov 2003 00:05:14 GMT  
 automatically naming a global variable

Quote:



>> If I have a string variable defined, how can I create a global
>> variable with the same name as the string?

>> For example:

>> >>> x = "variable_name'

>> Now I want to be able to use x to create a global variable whose
>> name is 'variable_name'

>setattr(sys.modules[__name__], x, 23) should work (if you
>have imported sys, of course).  A global variable is no more
>and no less than an attribute on your current module object,
>after all.  sys.modules[__name__] is one way to say "the
>module this code is in" (there are other ways).

>But this is hardly ever appropriate.  Generally, on digging
>a bit deeper, it turns out that whatever problem you think
>you're solving is better solved otherwise -- generally by
>more explicitly using a dictionary, as it happens (objects
>taking arbitrarily-named attributes, such as modules for
>example, implicitly use dictionaries, too).

I have sets that are described by a list of attributes and
properties that are implemented using python dictionaries.
One of a set's attributes is its name.  I need to provide
the user with a mechanism for referring to a dictionary that
represents a set, by using the set's name.  The user does
not want to have to reference the set via something like:

        sets['set_name']

They need to have a variable that references to the dictionary
for the set by simply using set_name.

I need to be able do this:

set_name = sets['set_name'], so that:

Quote:
>>> set_name

and

Quote:
>>> sets['set_name']

reference exactly the same thing.


Sun, 09 Nov 2003 00:47:23 GMT  
 automatically naming a global variable

Quote:
> If I have a string variable defined, how can I create a global
> variable with the same name as the string?

> For example:

> >>> x = "variable_name'

> Now I want to be able to use x to create a global variable whose
> name is 'variable_name'

Can someone explain to me why this question comes up so often?

(The answer is something like - this is a bad idea, use a dictionary).

What use is a global variable that you don't know the name of, so you have
to use <insert favorite hack here> once more to get to its value?

--
Remco Gerlich



Sun, 09 Nov 2003 03:00:50 GMT  
 automatically naming a global variable

Quote:

> > If I have a string variable defined, how can I create a global
> > variable with the same name as the string?

> > For example:

> > >>> x = "variable_name'

> > Now I want to be able to use x to create a global variable whose
> > name is 'variable_name'

> Can someone explain to me why this question comes up so often?

> (The answer is something like - this is a bad idea, use a dictionary).

It might not be such a bad idea in some cases.  Consider a module with
functions like these:

def do_a():
  try:
    something.a()
  except SomeError:
    pass

def do_b():
  try:
    something.b()
  except SomeError:
    pass

Functions 'do_a' and 'do_b' are structurally very similar.  Now suppose that
you have a whole bunch of these functions, and they're quite a bit bigger.
You want to minimize the amount of effort involved in adding new similar
functions.  You also want to minimize the amount of effort involved in
changing all of these functions in a similar way.  You do this by factoring
out the commonality:

def do(name):
  try:
    getattr(something, name)()
  except SomeError:
    pass

def do_a():
  do('a')

def do_b():
  do('b')

However, this code still contains redundancy, which is a potential source of
errors.  The redundancy can be removed by acting directly on the namespace
dictionary:

for name in ('a', 'b'):
  def f(name=name):
    try:
      getattr(something, name)()
    except SomeError:
      pass
  globals()['do_' + name'] = f

This code may be less readable than the original, but it meets the design
goal of minimizing the amount of effort it takes to add a new similar
function.  Note that simply using a new dictionary instead of 'globals()' is
not an option because it changes the interface of the module.  Also note
that there is no more danger of a name collision than in any other module.

--

Shareware computer games           -           http://rainerdeyke.com
"In ihren Reihen zu stehen heisst unter Feinden zu kaempfen" - Abigor



Sun, 09 Nov 2003 05:17:30 GMT  
 automatically naming a global variable

    ...

Quote:
> I have sets that are described by a list of attributes and
> properties that are implemented using python dictionaries.
> One of a set's attributes is its name.  I need to provide
> the user with a mechanism for referring to a dictionary that
> represents a set, by using the set's name.  The user does
> not want to have to reference the set via something like:

> sets['set_name']

So far, so good.

Quote:
> They need to have a variable that references to the dictionary
> for the set by simply using set_name.

Naah!  What they need is to have an object that groups
all sets, and use set.name rather than set_name for their
references.

Quote:
> I need to be able do this:

> set_name = sets['set_name'], so that:

> >>> set_name

> and

> >>> sets['set_name']

> reference exactly the same thing.

class SetOfSets:
    def __init__(self, refdict):
        self.__ref = refdict
    def __getattr__(self, name):
        return self.__ref[name]
set = SetOfSets(sets)

That's it.  Now, sets['name'] and set.name
reference exactly the same thing forevermore.
If you INSIST on the 'set_' prefix for the key
in dictionary sets, just change the last line
of the SetOfSets classbody to:
        return self.__ref['set_'+name]
though I'm not sure what this buys you.

This way you avoid all kinds of problems typical
of the overuse of globals -- such as the user not
religiously using the set_ stropping-prefix and
accidentally hiding builtins such as 'len()' by
naming a set that way...

If you INSIST on creating such horrible problems
for your users, as I said, then

    setattr(sys.modules[__name__],
        'set_name', sets['set_name'])

lets you do that for one name at a time, or even

    sys.modules[__name__].__dict__.update(sets)

for faster, mass-slaughter kind of suicide:-).

(PS, if the 'user code' in question is something you
are handling with eval, or exec, or execfile, etc,
you can pass arbitrary dictionaries to it -- then,
preparing an artificial dictionary of "globals" which
includes your 'dictionary of sets' is a far more
sensible approach than damaging the actual dict
of globals... similarly, you can use new.function or
other techniques to tweak the globals for user
functions that you get as function-objects, etc...).

Alex



Sun, 09 Nov 2003 05:13:31 GMT  
 automatically naming a global variable

Quote:



> > If I have a string variable defined, how can I create a global
> > variable with the same name as the string?

> > For example:

> >>>> x = "variable_name'

> > Now I want to be able to use x to create a global variable whose
> > name is 'variable_name'

> Have you stopped to consider that this may be a *bad* idea, and perhaps
> there is a better way to achieve whatever you want to do?
> Much better would be to create a dictionary to hold your unknown variables:

> mydict = {}
> mydict[x] = 'some value'

> That way you keep all these values with unknown names together and well
> clear of everything else.

> If you still want to modify globals() indirectly, you can do it:
> mydict = globals()
> mydict[x] = 'some value'

Or an alternative is an empty class that doesn't do anything.

class Variable:
        pass

Create an instance, and whenever you want to create a named variable,
set it as an attribute of your empty.

variable = Variable

variable.var1 = 'var1'
variable.var2 = 'var2'

Because class instances use a dictionary internally to store attributes,
this is the same thing as the post above, but with a slightly different
syntax. If you want to create variables that are definable only once,
and are resistant to overwriting,

Quote:
>>> class Variable:

        def __setattr__(self,key,value):
                if self.__dict__.has_key(key):
                        raise KeyError, "Key has already been defined"
                else:
                        self.__dict__[key] = value

Quote:
>>> variable = Variable()
>>> variable.var1 = 'var1'
>>> variable.var1 = 'variable1'

Traceback (most recent call last):
  File "<pyshell#27>", line 1, in ?
    variable.var1 = 'variable1'
  File "<pyshell#24>", line 4, in __setattr__
    raise KeyError, "Key has already been defined"
KeyError: Key has already been defined

Lots of fun. :|)

Joal Heagney/AncientHart



Mon, 10 Nov 2003 01:02:03 GMT  
 automatically naming a global variable
On 22 May 2001 19:00:50 GMT, Remco Gerlich

Quote:


>> If I have a string variable defined, how can I create a global
>> variable with the same name as the string?

>> For example:

>> >>> x = "variable_name'

>> Now I want to be able to use x to create a global variable whose
>> name is 'variable_name'

> Can someone explain to me why this question comes up so often?

> (The answer is something like - this is a bad idea, use a dictionary).

> What use is a global variable that you don't know the name of, so you have
> to use <insert favorite hack here> once more to get to its value?

In some other languages, this is "how it's done".  For instance,
in TCL, there are "array" variables, which are names of the form
array(key), and correspond roughly to Python dictionaries.
To say "the value of <name>", you write "$name", where name is defined
in the current scope.

In tcl, arrays can only be passed by name .. For instance, one might
write

        proc setitem { arrayname keyname value } {
                upvar $arrayname array
                set array(keyname) value
        }

        proc getitem { arrayname keyname } {
                upvar $arrayname array
                return $array(keyname)
        }

        setitem myarray 1 "hi there"
        puts $myarray(1)  ;#prints "hi there"

--- the "upvar" statement says "let me refer to the thing with the name
of the first argument in the caller's scope when I use the name given in
the second argument.

Talk about gross!  But, anyhow, I suspect it's for desire of something
like "upvar" that people keep asking this question, although a similar
idea probably exists in other languages.

Jeff



Tue, 11 Nov 2003 20:12:58 GMT  
 
 [ 9 post ] 

 Relevant Pages 

1. Global replace of variable names

2. Passing global variable names trough nested procs

3. Class variables / global variables / Init variables

4. Using a variable name for a variable name??

5. Namespace name and global name

6. Automatically declaring a global object

7. Global Variable / Sessions / ASP Application type Variable

8. field name and key name as a variable

9. field name and key name as a variable

10. FYI: Automatically BIND variables

11. Defining variables automatically

12. variable contents to variable name

 

 
Powered by phpBB® Forum Software