scope of variables

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Gary Wessle

    #1

    scope of variables

    Hi

    is the code below correct?

    b = 3
    def adding(a)
    print a + b

    it seams not to see the up-level scope where b is defined.

    thanks
  • Marc 'BlackJack' Rintsch

    #2
    Re: scope of variables

    In <874q06bz4c.fsf @localhost.loca ldomain>, Gary Wessle wrote:
    [color=blue]
    > is the code below correct?[/color]

    No...
    [color=blue]
    > b = 3
    > def adding(a)[/color]

    ....a colon is missing at the end of the above line.
    [color=blue]
    > print a + b
    >
    > it seams not to see the up-level scope where b is defined.[/color]

    It does. And you could easily find out yourself by just trying that code.
    Running this::

    b = 3
    def adding(a):
    print a + b

    adding(5)

    Puts out 8 as expected.

    Ciao,
    Marc 'BlackJack' Rintsch

    Comment

    • Steve R. Hastings

      #3
      Re: scope of variables

      On Thu, 04 May 2006 07:02:43 +1000, Gary Wessle wrote:[color=blue]
      > b = 3
      > def adding(a)
      > print a + b
      >
      > it seams not to see the up-level scope where b is defined.[/color]

      Assuming you put a ':' after the "def adding(a)", this should work in
      recent versions of Python. In Python 2.0 and older, this will not work.


      In Python 2.1, it will only work if you do this:

      from __future__ import nested_scopes


      When you first start Python interactively, it should print version
      information. Here's what my Python prints when I start it:

      Python 2.4.3 (#2, Apr 27 2006, 14:43:58)
      [GCC 4.0.3 (Ubuntu 4.0.3-1ubuntu5)] on linux2
      Type "help", "copyright" , "credits" or "license" for more information.


      As you can see, I'm running Python 2.4.3. Make sure you aren't running an
      old version of Python, and that code should do what you expect.
      --
      Steve R. Hastings "Vita est"
      steve@hastings. org http://www.blarg.net/~steveha

      Comment

      • Ben Finney

        #4
        Re: scope of variables

        Gary Wessle <phddas@yahoo.c om> writes:
        [color=blue]
        > is the code below correct?[/color]

        It's best to post an example that you've tried yourself, and that is
        small but completely demonstrates the issue in question.
        [color=blue]
        > b = 3
        > def adding(a)
        > print a + b[/color]

        This, for example, would fail the syntax check (the 'def' statement
        needs a trailing colon). After that's fixed, the code runs, but shows
        no output.

        A complete, minimal, working example will help people answer your
        question.

        --
        \ "[W]e are still the first generation of users, and for all that |
        `\ we may have invented the net, we still don't really get it." |
        _o__) -- Douglas Adams |
        Ben Finney

        Comment

        • Gary Wessle

          #5
          Re: scope of variables

          "Steve R. Hastings" <steve@hastings .org> writes:
          [color=blue]
          > On Thu, 04 May 2006 07:02:43 +1000, Gary Wessle wrote:[color=green]
          > > b = 3
          > > def adding(a)
          > > print a + b
          > >
          > > it seams not to see the up-level scope where b is defined.[/color]
          >
          > Assuming you put a ':' after the "def adding(a)", this should work in
          > recent versions of Python. In Python 2.0 and older, this will not work.[/color]

          the example was an in-accuretlly representation of a the problem I am
          having. my apologies.

          a = []
          def prnt():
          print len(a)
          [color=blue][color=green][color=darkred]
          >>> prnt[/color][/color][/color]
          <function prnt at 0xb7dc21b4>

          I expect to get 0 "the length of list a"

          Comment

          • Leif K-Brooks

            #6
            Re: scope of variables

            Gary Wessle wrote:[color=blue]
            > the example was an in-accuretlly representation of a the problem I am
            > having. my apologies.
            >
            > a = []
            > def prnt():
            > print len(a)
            >[color=green][color=darkred]
            >>>> prnt[/color][/color]
            > <function prnt at 0xb7dc21b4>
            >
            > I expect to get 0 "the length of list a"[/color]

            Python requires parenthesis to call a function.
            [color=blue][color=green][color=darkred]
            >>> a = []
            >>> def prnt():[/color][/color][/color]
            ... print len(a)
            ...[color=blue][color=green][color=darkred]
            >>> prnt[/color][/color][/color]
            <function prnt at 0xb7dcad84>[color=blue][color=green][color=darkred]
            >>> prnt()[/color][/color][/color]
            0

            Comment

            • Lord Landon

              #7
              Re: scope of variables

              Try >>> prnt()
              o.o'

              On 04 May 2006 08:25:01 +1000, Gary Wessle <phddas@yahoo.c om> wrote:[color=blue]
              > "Steve R. Hastings" <steve@hastings .org> writes:
              >[color=green]
              > > On Thu, 04 May 2006 07:02:43 +1000, Gary Wessle wrote:[color=darkred]
              > > > b = 3
              > > > def adding(a)
              > > > print a + b
              > > >
              > > > it seams not to see the up-level scope where b is defined.[/color]
              > >
              > > Assuming you put a ':' after the "def adding(a)", this should work in
              > > recent versions of Python. In Python 2.0 and older, this will not work..[/color]
              >
              > the example was an in-accuretlly representation of a the problem I am
              > having. my apologies.
              >
              > a = []
              > def prnt():
              > print len(a)
              >[color=green][color=darkred]
              > >>> prnt[/color][/color]
              > <function prnt at 0xb7dc21b4>
              >
              > I expect to get 0 "the length of list a"
              > --
              > http://mail.python.org/mailman/listinfo/python-list
              >[/color]


              --
              Lord Landon rules over all!

              Comment

              • Ryan Forsythe

                #8
                Re: scope of variables

                Gary Wessle wrote:[color=blue]
                > the example was an in-accuretlly representation of a the problem I am
                > having. my apologies.
                >
                > a = []
                > def prnt():
                > print len(a)
                >[color=green][color=darkred]
                >>>> prnt[/color][/color]
                > <function prnt at 0xb7dc21b4>
                >
                > I expect to get 0 "the length of list a"[/color]

                You want prnt(), not prnt:
                [color=blue][color=green][color=darkred]
                >>> a = []
                >>> def prnt():[/color][/color][/color]
                .... print len(a)
                ....[color=blue][color=green][color=darkred]
                >>> prnt[/color][/color][/color]
                <function prnt at 0x43c70>[color=blue][color=green][color=darkred]
                >>> prnt()[/color][/color][/color]
                0

                --Ryan

                Comment

                • Rob E

                  #9
                  Re: scope of variables

                  > is the code below correct?[color=blue]
                  >
                  > b = 3
                  > def adding(a)
                  > print a + b
                  >
                  > it seams not to see the up-level scope where b is defined.[/color]

                  Yes except for the missing : at the end of the "def" line.

                  Rob

                  Comment

                  • Gary Wessle

                    #10
                    Re: scope of variables

                    Ryan Forsythe <ryan@cs.uorego n.edu> writes:
                    [color=blue]
                    > Gary Wessle wrote:[color=green]
                    > > the example was an in-accuretlly representation of a the problem I am
                    > > having. my apologies.
                    > >
                    > > a = []
                    > > def prnt():
                    > > print len(a)
                    > >[color=darkred]
                    > >>>> prnt[/color]
                    > > <function prnt at 0xb7dc21b4>
                    > >
                    > > I expect to get 0 "the length of list a"[/color]
                    >
                    > You want prnt(), not prnt:
                    >[/color]

                    I finally was able to duplicate the error with a through away code
                    as follows,

                    *************** *************** *************** *************** ****
                    acc = [1,2,3]

                    def a():
                    b = [4, 5, 6]
                    acc = acc + b
                    print len(acc)

                    a()

                    *************** * error *************** *
                    Traceback (most recent call last):
                    File "a.py", line 12, in ?
                    a()
                    File "a.py", line 9, in a
                    acc = acc + b
                    UnboundLocalErr or: local variable 'acc' referenced before assignment

                    Comment

                    • bruno at modulix

                      #11
                      Re: scope of variables

                      Gary Wessle wrote:[color=blue]
                      > Ryan Forsythe <ryan@cs.uorego n.edu> writes:
                      >
                      >[color=green]
                      >>Gary Wessle wrote:
                      >>[color=darkred]
                      >>>the example was an in-accuretlly representation of a the problem I am
                      >>>having. my apologies.
                      >>>[/color][/color][/color]
                      (snip)[color=blue]
                      > I finally was able to duplicate the error with a through away code
                      > as follows,
                      >
                      > *************** *************** *************** *************** ****
                      > acc = [1,2,3]
                      >
                      > def a():
                      > b = [4, 5, 6]
                      > acc = acc + b
                      > print len(acc)
                      >
                      > a()
                      >
                      > *************** * error *************** *
                      > Traceback (most recent call last):
                      > File "a.py", line 12, in ?
                      > a()
                      > File "a.py", line 9, in a
                      > acc = acc + b
                      > UnboundLocalErr or: local variable 'acc' referenced before assignment[/color]

                      This is a FAQ:
                      Contents: Programming FAQ- General questions- Is there a source code-level debugger with breakpoints and single-stepping?, Are there tools to help find bugs or perform static analysis?, How can I c...


                      For short: if a name is 'assigned' (in Python, the correct term is
                      'bound') in the local scope, it'll be considered a local name. If it's
                      *only* accessed, it'll be looked up in the enclosing namespace - here
                      the so-called 'global' (which means: 'module') namespace.

                      The dirty solution is to declare 'acc' as global in the function:
                      def a():
                      b = [4, 5, 6]
                      global acc
                      acc = acc + b
                      print len(acc)

                      but this is really BadCode(tm). As a general rule, functions should not
                      silently modify or rebind global variables - this leads to maintenance
                      nightmares. In this case, you should manage to either 1/ pass acc as a
                      param to a(), or 2/ have a() return the sequence to be added to acc:

                      # 1
                      acc = [1,2,3]
                      def a(alist):
                      alist.extend([4, 5, 6])
                      return alist

                      acc = a(acc)
                      print acc, len(acc)

                      # 2
                      acc = [1,2,3]
                      def a():
                      return [4, 5, 6]

                      acc.extend(a())
                      print acc, len(acc)


                      The Right Thing(tm) to do of course depends on the real code, so it may
                      be yet another solution, but it's impossible to decide with dummy code...

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

                      Comment

                      • Gary Wessle

                        #12
                        Re: scope of variables

                        thank you

                        Comment

                        Working...