Create a variable "on the fly"

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Paul D.Smith

    Create a variable "on the fly"

    Can Python create a variable "on-the-fly". For example I would like
    something like...

    make_variable(' OSCAR', 'the grouch');
    print OSCAR;

    ....to output...

    the grouch

    Anything like this in Python?

    And in case anyone is interested, I want to instantiate a set of variables
    based on environment variables without using os.environ everywhere by having
    a look instantiate Python variables of the appropriate type.

    Thanks,
    Paul DS.

    --
    Please remove the "x-" if replying to sender.


  • Paolino

    #2
    Re: Create a variable "on the fly"

    Paul D.Smith wrote:[color=blue]
    > Can Python create a variable "on-the-fly". For example I would like
    > something like...
    >
    > make_variable(' OSCAR', 'the grouch');
    > print OSCAR;
    >
    > ...to output...[/color]
    Python has only 'on the fly' variables and ';' is not used for one
    expression in one line.


    Probably the tutorial is good to be read also.

    Paolino





    _______________ _______________ _____
    Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB

    Comment

    • Dan

      #3
      Re: Create a variable "on the fly"

      > make_variable(' OSCAR', 'the grouch');[color=blue]
      > print OSCAR;[/color]

      Try using "setattr". (It's in __builtins__; you don't have to import
      anything.)
      [color=blue][color=green][color=darkred]
      >>> print setattr.__doc__[/color][/color][/color]
      setattr(object, name, value)

      Set a named attribute on an object; setattr(x, 'y', v) is equivalent to
      ``x.y = v''.

      --
      If builders built buildings the way programmers write programs,
      the first woodpecker that came along would destroy civilization.
      - Original author unknown


      Comment

      • Paolino

        #4
        Re: Create a variable "on the fly"

        Paul D.Smith wrote:[color=blue]
        > Can Python create a variable "on-the-fly". For example I would like
        > something like...
        >
        > make_variable(' OSCAR', 'the grouch');
        > print OSCAR;
        >
        > ...to output...[/color]
        Python has only 'on the fly' variables and ';' is not used for one
        expression in one line.


        Probably the tutorial is good to be read also.

        Paolino

        Comment

        • Steve M

          #5
          Re: Create a variable "on the fly"

          PythonWin 2.3.5 (#62, Feb 9 2005, 16:17:08) [MSC v.1200 32 bit
          (Intel)] on win32.
          Portions Copyright 1994-2004 Mark Hammond (mhammond@skipp inet.com.au) -
          see 'Help/About PythonWin' for further copyright information.[color=blue][color=green][color=darkred]
          >>> locals()['OSCAR'] = 'the grouch'
          >>> OSCAR[/color][/color][/color]
          'the grouch'[color=blue][color=green][color=darkred]
          >>>[/color][/color][/color]

          Comment

          • bruno modulix

            #6
            Re: Create a variable "on the fly"

            Paul D.Smith wrote:[color=blue]
            > Can Python create a variable "on-the-fly". For example I would like
            > something like...
            >
            > make_variable(' OSCAR', 'the grouch');
            > print OSCAR;
            >
            > ...to output...
            >
            > the grouch
            >
            > Anything like this in Python?[/color]

            The bad news is that yes, there is something "like this" in Python.

            The good news is that I won't tell you more about it, since it's a very
            bad practice(tm). The good practice is to put your vars in a dict.
            [color=blue]
            > And in case anyone is interested, I want to instantiate a set of variables
            > based on environment variables without using os.environ everywhere[/color]

            env = os.environ

            Now you just have to look at env['MY_ENV_VAR'] !-)
            [color=blue]
            > by having
            > a look instantiate Python variables of the appropriate type.[/color]

            What do you mean "of the appropriate type" ? You want to typecast (eg.
            from string to numeric) ? Then you need to know what env var must be
            casted to what type ? Then you don't need to create variables 'on the fly' ?

            I must have missed something...


            --
            bruno desthuilliers
            python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
            p in 'onurb@xiludom. gro'.split('@')])"

            Comment

            • Willem Broekema

              #7
              Re: Create a variable "on the fly"

              Steve M:[color=blue][color=green][color=darkred]
              > >>> locals()['OSCAR'] = 'the grouch'
              > >>> OSCAR[/color][/color]
              > 'the grouch'[color=green][color=darkred]
              > >>>[/color][/color][/color]

              Use "globals", not "locals":

              globals()['OSCAR'] = 'the grouch'

              because <http://www.python.org/doc/current/lib/built-in-funcs.html>
              states:

              locals()
              Update and return a dictionary representing the current local symbol
              table. Warning: The contents of this dictionary should not be
              modified; changes may not affect the values of local variables used
              by the interpreter.

              Function globals() is not subject to this restriction.


              - Willem

              Comment

              • Do Re Mi chel La Si Do

                #8
                Re: Create a variable &quot;on the fly&quot;

                Hi !

                Try :

                OSCAR='the grouch'
                print OSCAR


                useless to thank me

                Michel Claveau


                Comment

                • Paul D.Smith

                  #9
                  Re: Create a variable &quot;on the fly&quot;

                  Bruno,

                  FYI, notes in-line...

                  Cheers,
                  Paul DS
                  [color=blue][color=green]
                  > > a look instantiate Python variables of the appropriate type.[/color]
                  >
                  > What do you mean "of the appropriate type" ? You want to typecast (eg.
                  > from string to numeric) ? Then you need to know what env var must be
                  > casted to what type ? Then you don't need to create variables 'on the fly'[/color]
                  ?[color=blue]
                  >
                  > I must have missed something...[/color]

                  Good point - my Python "nomenclatu re" is still in its infancy. The
                  background is that I've inherited some historical Python scripts that need
                  to be configured from a bash shell script (as these Python scripts are being
                  integrated into a bigger system driven by shell scripts and with a
                  pre-existing single "point-of-configuration") instead of the existing
                  Pything config script. The existing Python script configures these
                  parameters thus...

                  PARM1='Fred'
                  PARM2=12
                  ....

                  So I could so the following...

                  PARM1=os.enviro n['PARM1']
                  PARM2=os.enviro n['PARM2']
                  ....

                  The problem is that this config file is almost certainly not complete (as
                  the complete integration of all scripts has not been done) and I don't want
                  to spend my life tweaking not one config file (the shell script), but two
                  (the shell script and the Python script).

                  Now I'm helped because in fact the parameters have a common format e.g.

                  MY_PARM1...
                  MY_PARM2...

                  so I can define shell environment variables with the same names and then
                  look for any parameter defined in the shell and named "MY_..." and
                  instantiate the Python variable from that.

                  What I'm left with is the following...

                  1. A shell script which I maintain.
                  2. A simple Python config which searches for all shell environment variables
                  named "MY_..." and instantiates then as Python variables.
                  3. Historical scripts that run without me needing to spend time hunting down
                  all the config variables and replacing them with os.environ['MY_...'].

                  Agreed that long term this is not good practice, but short term it's a time
                  save.


                  Comment

                  • Sybren Stuvel

                    #10
                    Re: Create a variable &quot;on the fly&quot;

                    Paul D.Smith enlightened us with:[color=blue]
                    > The background is that I've inherited some historical Python scripts
                    > that need to be configured from a bash shell script [...] instead of
                    > the existing Pything config script. [...] The problem is that this
                    > config file is almost certainly not complete [...] and I don't want
                    > to spend my life tweaking not one config file (the shell script),
                    > but two (the shell script and the Python script).[/color]

                    So basically you want environment variables to be able to alter Python
                    variables. This is not a smart move. It's the same as the
                    'register_globa ls' functionality in PHP. Read
                    http://us2.php.net/register_globals for more information.
                    [color=blue]
                    > 2. A simple Python config which searches for all shell environment
                    > variables named "MY_..." and instantiates then as Python variables.[/color]

                    Why don't you just copy all MY_... environment variables from
                    os.environ to the dict which holds your configuration? Or are you
                    storing your entire configuration in global variables? A dict would be
                    a much cleaner and more extendible solution.

                    Sybren
                    --
                    The problem with the world is stupidity. Not saying there should be a
                    capital punishment for stupidity, but why don't we just take the
                    safety labels off of everything and let the problem solve itself?
                    Frank Zappa

                    Comment

                    • Steven Bethard

                      #11
                      Re: Create a variable &quot;on the fly&quot;

                      Paul D.Smith wrote:[color=blue]
                      > 2. A simple Python config which searches for all shell environment variables
                      > named "MY_..." and instantiates then as Python variables.[/color]

                      my_vars = dict((k, v)
                      for k, v in os.environ.iter items()
                      if k.startswith('M Y_'))
                      globals().updat e(my_vars)

                      If you ever refactor the code, I'd suggest writing a single
                      configuration file instead of setting environment variables, and reading
                      that configuration file in each script that needs it. Generally I've
                      found that relying on environment variables being set is hard to
                      maintain and a real pain when you have to move to a new system.

                      STeVe

                      Comment

                      • Scott David Daniels

                        #12
                        Re: Create a variable &quot;on the fly&quot;

                        Paul D.Smith wrote:[color=blue]
                        >... What I'm left with is the following...
                        > 1. A shell script which I maintain.
                        > 2. A simple Python config which searches for all shell environment variables
                        > named "MY_..." and instantiates then as Python variables.
                        > 3. Historical scripts that run without me needing to spend time hunting down
                        > all the config variables and replacing them with os.environ['MY_...'].[/color]

                        Suppose you have a module named 'MY', with MY.py as:

                        import os
                        _globals = globals()
                        for _name, _entry in os.environ.iter items():
                        if _name.startswit h('MY_'):
                        try:
                        _entry = int(_entry)
                        except ValueError:
                        try:
                        _entry = float(_entry)
                        except ValueError:
                        pass
                        _globals[_name[3 :]] = _entry

                        then, wherever your python scripts use MY_XYZ, you begin the script
                        with "import MY" and change every "MY_XYZ" to "MY.XYZ".


                        --Scott David Daniels
                        Scott.Daniels@A cm.Org

                        Comment

                        Working...