sort of a beginner question about globals

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • fred.dixon

    #1

    sort of a beginner question about globals

    i have read the book and searched the group too
    ----------------------------------------------
    im not gettin it.
    i want to read a global (OPTIONS) from file1 from a class method
    (func1) in file2
    i want to understand how this works.


    ----------------------------------------------
    #file1.py
    import file2
    import sys

    OPTION = sys.argv[1:]
    pass
    a=global2.class 1()
    a.func1()


    #file2.py
    import __main__
    pass
    class class1:
    .. def func1(self):
    .. pass
    -------------------------------------------

  • Steven Bethard

    #2
    Re: sort of a beginner question about globals

    fred.dixon wrote:[color=blue]
    > i have read the book and searched the group too
    > ----------------------------------------------
    > im not gettin it.
    > i want to read a global (OPTIONS) from file1 from a class method
    > (func1) in file2
    > i want to understand how this works.
    >
    > ----------------------------------------------
    > #file1.py
    > import file2
    > import sys
    >
    > OPTION = sys.argv[1:]
    > pass
    > a=global2.class 1()
    > a.func1()
    >
    >
    > #file2.py
    > import __main__
    > pass
    > class class1:
    > . def func1(self):
    > . pass
    > -------------------------------------------[/color]

    ----- file1.py -----
    import file2

    a = file2.class1()
    a.func1()
    --------------------

    ----- file2.py -----
    class class1(object):
    def func1(self):
    pass
    --------------------

    I don't see what you want OPTION for, so I've removed it. If you can
    explain your intentions better, maybe I can help more.

    STeVe

    Comment

    • fred.dixon

      #3
      Re: sort of a beginner question about globals

      I want to use OPTIONS as a global var.
      In this particular case I am trying to set a global debug constant so I
      can have some debug logging happen when my program is run with a
      -debug option.
      what will actuall end up in OPTIONS is OPTIONS.debug = True as i am
      using optparse module.

      Comment

      • Steven Bethard

        #4
        Re: sort of a beginner question about globals

        fred.dixon wrote:[color=blue]
        > I want to use OPTIONS as a global var.
        > In this particular case I am trying to set a global debug constant so I
        > can have some debug logging happen when my program is run with a
        > -debug option.
        > what will actuall end up in OPTIONS is OPTIONS.debug = True as i am
        > using optparse module.[/color]

        Why not just make options a module?

        Then you can do something like:

        ----- options.py -----
        debug = False
        ----------------------

        ----- file1.py -----
        import file2
        import options

        options.debug = True
        a = file2.class1()
        a.func1()
        --------------------

        ----- file2.py -----
        import options
        class class1(object):
        def func1(self):
        if options.debug:
        print 'Debugging'
        pass
        --------------------

        Note that if you're trying to output debugging messges, you should
        really look into the logging module instead.

        STeVe

        Comment

        • fred.dixon

          #5
          Re: sort of a beginner question about globals

          how would i use the following if OPTIONS was in a module ?
          -----------------------
          from optparse import OptionParser

          usage = "usage: %prog [options] arg"
          parser = OptionParser(us age)

          parser.add_opti on("-d", "--debug", ction="store_tr ue", dest="verbose")
          (OPTIONS = parser.parse_ar gs()

          ps
          Im not anywhere near my program right now just doing some kunch time
          surfing.

          Comment

          • Steven Bethard

            #6
            Re: sort of a beginner question about globals

            fred.dixon wrote:[color=blue]
            > how would i use the following if OPTIONS was in a module ?
            > -----------------------
            > from optparse import OptionParser
            >
            > usage = "usage: %prog [options] arg"
            > parser = OptionParser(us age)
            >
            > parser.add_opti on("-d", "--debug", ction="store_tr ue", dest="verbose")
            > (OPTIONS = parser.parse_ar gs()[/color]

            Just have this code update the options module:

            import options
            ....
            opts, args = parser.parse_ar gs()
            options.__dict_ _.update(opts._ _dict__)

            STeVe

            Comment

            • fred.dixon

              #7
              Re: sort of a beginner question about globals

              ok I'm sorry, I'm not sure what your doing there.
              if i have to guess it looks like yo might me modifying the imported
              modules dict with another dict.

              isn't there a way i can just assign to a var and have it seen no matter
              what part of the code is currently executing ?

              Comment

              • fred.dixon

                #8
                Re: sort of a beginner question about globals

                it seems that i can import __main__ where i set the global and then
                access the var from my local func.

                is ther any gotcha's involveld in this ?

                Comment

                • Steven Bethard

                  #9
                  Re: sort of a beginner question about globals

                  fred.dixon wrote:[color=blue]
                  > ok I'm sorry, I'm not sure what your doing there.
                  > if i have to guess it looks like yo might me modifying the imported
                  > modules dict with another dict.[/color]

                  Yes, this takes all the atrributes of the options object and sets them
                  as attributes of the module. If you're afraid of __dict__, you could
                  also write this as:

                  for name, value in vars(opts).iter items():
                  setitem(options , name, value)
                  [color=blue]
                  > isn't there a way i can just assign to a var and have it seen no matter
                  > what part of the code is currently executing ?[/color]

                  No, unless you mean only within a single module. Python has no globals
                  in the sense of being global to all modules. If globals in a single
                  module is sufficient, you can modify the globals of the current module
                  using globals(), e.g.:

                  globals()[name] = value

                  or in my example:

                  globals().updat e(vars(opts))

                  You can also do this by importing the module itself, e.g.:

                  mod = __import__(__na me__)
                  setattr(mod, name, value)
                  [color=blue]
                  > it seems that i can import __main__ where i set the global and then
                  > access the var from my local func.
                  >
                  > is ther any gotcha's involveld in this ?[/color]

                  Probably. ;) But since I don't know what code you've actually produced
                  here, I'm not sure. What did you write to "import __main__ ... [and]
                  set the gloabl and then access the var"?

                  STeVe

                  Comment

                  • fred.dixon

                    #10
                    Re: sort of a beginner question about globals

                    this is what i am using to test with.
                    my program is not much more involved just longer
                    and with a GUI.
                    I did test it and everything works, just wondered if there was
                    something evil and bad about importing main.
                    #------------------------------------------------
                    #global1.py
                    import global2
                    import global3
                    import sys

                    constant = 'dumb'
                    option = sys.argv[1:]
                    pass
                    #global2.func1( )
                    a=global2.class 1()
                    a.func1()
                    print newvar


                    #global2.py
                    import __main__
                    pass
                    class class1:
                    def func1(self):
                    __main__.newvar = "string"
                    pass

                    Comment

                    • Steven Bethard

                      #11
                      Re: sort of a beginner question about globals

                      fred.dixon wrote:[color=blue]
                      > #global1.py
                      > import global2
                      > import global3
                      > import sys
                      >
                      > constant = 'dumb'
                      > option = sys.argv[1:]
                      > pass
                      > #global2.func1( )
                      > a=global2.class 1()
                      > a.func1()
                      > print newvar
                      >
                      > #global2.py
                      > import __main__
                      > pass
                      > class class1:
                      > def func1(self):
                      > __main__.newvar = "string"
                      > pass[/color]

                      The other ways of getting this behavior would be to write global2.py as:
                      class class1:
                      def func1(self):
                      global newvar
                      newvar = "string"
                      or
                      class class1:
                      def func1(self):
                      globals()["newvar"] = "string"
                      or
                      class class1:
                      def func1(self):
                      __import__(__na me__).newvar = "string"
                      I don't know which of these is really preferred. Generally if I see
                      myself writing code like this, I figure I probably need to refactor things.

                      STeVe

                      P.S. Why are you writing all those 'pass' statements? They're not
                      necessary in any of the locations you've placed them.

                      Comment

                      • fred.dixon

                        #12
                        Re: sort of a beginner question about globals

                        when i am roughing out my functions and classes i out a pass statement
                        as my first line just as a place holder and a convenient place to put a
                        break when i am testing. no other good reason.

                        Comment

                        • Duncan Booth

                          #13
                          Re: sort of a beginner question about globals

                          fred.dixon wrote:
                          [color=blue]
                          > when i am roughing out my functions and classes i out a pass statement
                          > as my first line just as a place holder and a convenient place to put a
                          > break when i am testing. no other good reason.
                          >[/color]

                          A better idea when roughing out functions and classes is to insert a
                          docstring describing what the function is going to do. That way you don't
                          have to use 'pass' at all, and you don't have to remember to remove
                          anything when you later add code. Alternatively use 'raise
                          NotImplementedE rror' to tell you at runtime if you hit any such functions.

                          'convenient place to put a break when testing' implies you test by stepping
                          through with a debugger. You should consider writing unit tests as a way of
                          reducing the amount of debugging you need to do.

                          Comment

                          • fred.dixon

                            #14
                            Re: sort of a beginner question about globals

                            :) unit test is something on my to-learn list. seems involved and i
                            haven't seen any straight forward tutorials yet. as yet i still
                            consider myself a hobbyist at best.

                            Comment

                            • Thomas Heller

                              #15
                              Re: sort of a beginner question about globals

                              "fred.dixon " <fred.dixon@gma il.com> writes:
                              [color=blue]
                              > :) unit test is something on my to-learn list. seems involved and i
                              > haven't seen any straight forward tutorials yet. as yet i still
                              > consider myself a hobbyist at best.[/color]

                              I would recommend "Test Driven Development" by Kent Beck
                              (Addison-Wesley).

                              Thomas

                              Comment

                              Working...