Importing an output from another function

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

    #1

    Importing an output from another function

    Probably a stupid question, but I'm a newbie and this really pisses me
    off. Run this script:

    import random

    def Func1():
    choice = ('A', 'B', 'C')
    output = random.choice(c hoice)

    def Func2():
    print output

    Func1()
    Func2()

    And: an error message...... It says:

    Traceback (most recent call last):
    File "ptls-demo.py", line 11, in ?
    Func2()
    File "how -the-hell-do-i-fix-this.py", line 8, in Func2
    print output
    NameError: global name 'output' is not defined

    Obviosly, I need to import the variable 'output' from Func1() into
    Func2(), but how?

    Thanks in advance,
    -- /usr/bin/byte

  • bearophileHUGS@lycos.com

    #2
    Re: Importing an output from another function

    Generally, a name defined into a function can't be read outside of it,
    so you have to return the function result explicitely:

    import random

    def Func1():
    choice = ('A', 'B', 'C')
    output = random.choice(c hoice)
    return output

    def Func2(item):
    print item

    output1 = Func1()
    Func2(output1)


    Bye,
    bearophile

    Comment

    • Byte

      #3
      Re: Importing an output from another function

      Great, thanks

      -- /usr/bin/byte

      Comment

      • Byte

        #4
        Re: Importing an output from another function

        Now what do I do if Func1() has multiple outputs and Func2() requires
        them all to give its own output, as follows:

        import random

        def Func1():
        choice = ('A', 'B', 'C')
        output = random.choice(c hoice)
        output2 = random.choice(c hoice)
        return output
        return output2

        def Func2(item1, item2):
        print item1, item2

        output1 = Func1()
        Func2(output1)

        Thanks in advance,
        -- /usr/bin/byte

        Comment

        • John Salerno

          #5
          Re: Importing an output from another function

          Byte wrote:[color=blue]
          > Now what do I do if Func1() has multiple outputs and Func2() requires
          > them all to give its own output, as follows:[/color]

          You can return them as a tuple:
          [color=blue][color=green][color=darkred]
          >>> def func1():[/color][/color][/color]
          output1 = 'hi'
          output2 = 'bye'
          return (output1, output2)
          [color=blue][color=green][color=darkred]
          >>> def func2(data):[/color][/color][/color]
          print data
          [color=blue][color=green][color=darkred]
          >>> func2(func1())[/color][/color][/color]
          ('hi', 'bye')

          [color=blue]
          > def Func1():
          > choice = ('A', 'B', 'C')
          > output = random.choice(c hoice)
          > output2 = random.choice(c hoice)
          > return output
          > return output2[/color]

          Only the first return statement would run in that code.

          Comment

          • James Stroud

            #6
            Re: Importing an output from another function

            Byte wrote:[color=blue]
            > Now what do I do if Func1() has multiple outputs and Func2() requires
            > them all to give its own output, as follows:
            >
            > import random
            >
            > def Func1():
            > choice = ('A', 'B', 'C')
            > output = random.choice(c hoice)
            > output2 = random.choice(c hoice)
            > return output
            > return output2[/color]

            The function will return at "return output", so "return output2" will
            never be reached.

            [color=blue]
            > def Func2(item1, item2):
            > print item1, item2
            >
            > output1 = Func1()
            > Func2(output1)
            >
            > Thanks in advance,
            > -- /usr/bin/byte
            >[/color]

            Try this (I think its called "argument expansion", but I really don't
            know what its called, so I can't point you to docs):

            def Func1():
            choice = ('A', 'B', 'C')
            output = random.choice(c hoice)
            output2 = random.choice(c hoice)
            return output, output2

            def Func2(*items):
            print items

            output = Func1()
            Func2(output1)


            BETTER:
            =======

            You can also make a "generator" (which I have made generalized, which
            seems to be what you are striving for):


            def Gener1(num):
            choice = ('A', 'B', 'C')
            for i in xrange(num):
            yield random.choice(c hoice)

            def Func2(item):
            print item

            for item in Gener1(2):
            Func2(item)


            James

            --
            James Stroud
            UCLA-DOE Institute for Genomics and Proteomics
            Box 951570
            Los Angeles, CA 90095


            Comment

            • James Stroud

              #7
              Re: Importing an output from another function



              Byte wrote:[color=blue]
              > Now what do I do if Func1() has multiple outputs and Func2() requires
              > them all to give its own output, as follows:
              >
              > import random
              >
              > def Func1():
              > choice = ('A', 'B', 'C')
              > output = random.choice(c hoice)
              > output2 = random.choice(c hoice)
              > return output
              > return output2[/color]


              The function will return at "return output", so "return output2" will
              never be reached.
              [color=blue]
              > def Func2(item1, item2):
              > print item1, item2
              >
              > output1 = Func1()
              > Func2(output1)
              >
              > Thanks in advance,
              > -- /usr/bin/byte
              >[/color]


              Try this (I think its called "argument expansion", but I really don't
              know what its called, so I can't point you to docs):

              def Func1():
              choice = ('A', 'B', 'C')
              output = random.choice(c hoice)
              output2 = random.choice(c hoice)
              return output, output2

              def Func2(*items):
              print items

              output = Func1()
              Func2(*output1)


              BETTER:
              =======

              You can also make a "generator" (which I have made generalized, which
              seems to be what you are striving for):


              def Gener1(num):
              choice = ('A', 'B', 'C')
              for i in xrange(num):
              yield random.choice(c hoice)

              def Func2(item):
              print item

              for item in Gener1(2):
              Func2(item)


              James

              --
              James Stroud
              UCLA-DOE Institute for Genomics and Proteomics
              Box 951570
              Los Angeles, CA 90095


              Comment

              • John Salerno

                #8
                Re: Importing an output from another function

                James Stroud wrote:
                [color=blue]
                > Try this (I think its called "argument expansion", but I really don't
                > know what its called, so I can't point you to docs):
                >
                > def Func1():
                > choice = ('A', 'B', 'C')
                > output = random.choice(c hoice)
                > output2 = random.choice(c hoice)
                > return output, output2
                >
                > def Func2(*items):
                > print items
                >
                > output = Func1()
                > Func2(*output1)[/color]

                I was wondering about '*items' when I wrote my response. I left out the
                asterisk in my version and it still seems to work. Is it necessary?

                Comment

                • James Stroud

                  #9
                  Re: Importing an output from another function

                  John Salerno wrote:[color=blue]
                  > James Stroud wrote:
                  >[color=green]
                  >> Try this (I think its called "argument expansion", but I really don't
                  >> know what its called, so I can't point you to docs):
                  >>
                  >> def Func1():
                  >> choice = ('A', 'B', 'C')
                  >> output = random.choice(c hoice)
                  >> output2 = random.choice(c hoice)
                  >> return output, output2
                  >>
                  >> def Func2(*items):
                  >> print items
                  >>
                  >> output = Func1()
                  >> Func2(*output1)[/color]
                  >
                  >
                  > I was wondering about '*items' when I wrote my response. I left out the
                  > asterisk in my version and it still seems to work. Is it necessary?[/color]

                  Yours is better, after I wrote mine, I realized the asterisk was
                  unnecessary for this particular example, except that it makes Func2 more
                  general.

                  James

                  --
                  James Stroud
                  UCLA-DOE Institute for Genomics and Proteomics
                  Box 951570
                  Los Angeles, CA 90095


                  Comment

                  • John Salerno

                    #10
                    Re: Importing an output from another function

                    James Stroud wrote:
                    [color=blue]
                    > Yours is better, after I wrote mine, I realized the asterisk was
                    > unnecessary for this particular example, except that it makes Func2 more
                    > general.[/color]

                    Yeah, I tested it. Func2 prints a tuple of a tuple when the asterisk is
                    used.

                    But your generator still wins. :)

                    Comment

                    • James Stroud

                      #11
                      Re: Importing an output from another function

                      John Salerno wrote:[color=blue]
                      > James Stroud wrote:
                      >
                      > Try this (I think its called "argument expansion", but I really[/color]
                      don't[color=blue]
                      > know what its called, so I can't point you to docs):
                      >
                      > def Func1():
                      > choice = ('A', 'B', 'C')
                      > output = random.choice(c hoice)
                      > output2 = random.choice(c hoice)
                      > return output, output2
                      >
                      > def Func2(*items):
                      > print items
                      >
                      > output = Func1()
                      > Func2(*output1)
                      >
                      >
                      > I was wondering about '*items' when I wrote my response. I left out[/color]
                      the[color=blue]
                      > asterisk in my version and it still seems to work. Is it necessary?
                      >[/color]
                      Yours is better, after I wrote mine, I realized the asterisk was
                      unnecessary for this particular example, except that it makes Func2
                      more
                      general.

                      James

                      --
                      James Stroud
                      UCLA-DOE Institute for Genomics and Proteomics
                      Box 951570
                      Los Angeles, CA 90095



                      Comment

                      • Terry Hancock

                        #12
                        Re: Importing an output from another function

                        On 17 Mar 2006 12:15:28 -0800
                        "Byte" <eoinrogers@gma il.com> wrote:[color=blue]
                        > Probably a stupid question, but I'm a newbie and this
                        > really pisses me off. Run this script:
                        >
                        > import random
                        >
                        > def Func1():
                        > choice = ('A', 'B', 'C')
                        > output = random.choice(c hoice)
                        >
                        > def Func2():
                        > print output
                        >
                        > Func1()
                        > Func2()[/color]

                        Several possible solutions. The simplest (but least
                        informative):

                        """
                        import random

                        def Func1():
                        global output
                        choice = ('A', 'B', 'C')
                        output = random.choice(c hoice)

                        def Func2():
                        print output

                        Func1()
                        Func2()
                        """

                        i.e. make output a global variable

                        But as has already been pointed out, you aren't really using
                        the nature of functions here. Better:

                        """
                        import random

                        def Func1():
                        return random.choice(( 'A', 'B', 'C'))

                        def Func2(output):
                        print output

                        Func2(Func1())
                        """

                        You later ask about returning multiple values. Python is
                        pretty cool in this respect -- you can return multiple
                        values in a tuple, which can then be "unpacked"
                        automatically. This gives you a nice many-to-many idiom for
                        function calls, e.g.:

                        x, y = random_point(x_ min, x_max, y_min, y_max)

                        And if you need to pass that to a function which takes two
                        arguments (x,y), you can:

                        set_point(*rand om_point(x_min, x_max, y_min, y_max))

                        Of course, some people would rather see that expanded out,
                        and indeed, too many nested function calls can be hard on
                        the eyes, so you might want to do this anyway:

                        x, y = random_point(x_ min, x_max, y_min, y_max)
                        set_point(x, y)

                        or

                        P = random_point(x_ min, x_max, y_min, y_max)
                        set_point(P)

                        and of course, it's possible that the function requires the
                        arguments in a different order, e.g.:

                        x, y = random_point(1, 80,1,25)
                        set_rowcol(y, x, 'A')

                        or some such thing.

                        By far the coolest thing about tuple-unpacking, though, is
                        that this works like you'd expect it to:

                        x, y = y, x

                        instead of being a dumb mistake like this is:

                        x = y
                        y = x

                        which of course should be

                        temp = y
                        x = y
                        y = temp

                        But ewww that's ugly.

                        Cheers,
                        Terry

                        --
                        Terry Hancock (hancock@Anansi Spaceworks.com)
                        Anansi Spaceworks http://www.AnansiSpaceworks.com

                        Comment

                        • Paul Rubin

                          #13
                          Re: Importing an output from another function

                          "Byte" <eoinrogers@gma il.com> writes:[color=blue]
                          > Probably a stupid question, but I'm a newbie and this really pisses me
                          > off. Run this script:
                          >
                          > import random
                          >
                          > def Func1():
                          > choice = ('A', 'B', 'C')
                          > output = random.choice(c hoice)
                          >
                          > def Func2():
                          > print output
                          >
                          > Func1()
                          > Func2()[/color]

                          You could declare output to be global, but it's kind of poor style.
                          Preferable is something like:

                          def Func1():
                          choice = ('A', 'B', 'C')
                          output = random.choice(c hoice)
                          return output

                          def Func2(x):
                          print x

                          output = Func1() # this "output" is not the same as the one in Func1
                          Func2(output)

                          Comment

                          • Ben Cartwright

                            #14
                            Re: Importing an output from another function

                            James Stroud wrote:[color=blue]
                            > Try this (I think its called "argument expansion", but I really don't
                            > know what its called, so I can't point you to docs):
                            >
                            > def Func1():
                            > choice = ('A', 'B', 'C')
                            > output = random.choice(c hoice)
                            > output2 = random.choice(c hoice)
                            > return output, output2
                            >
                            > def Func2(*items):
                            > print items
                            >
                            > output = Func1()
                            > Func2(*output1)[/color]


                            Single asterisk == "arbitrary argument list". Useful in certain
                            patterns, but not something you use every day.

                            Documentation is in the tutorial:


                            PS: Like "self" for class instance methods, "*args" is the
                            conventional name of the arbitrary argument list.

                            --Ben

                            Comment

                            • Byte

                              #15
                              Re: Importing an output from another function

                              "Try this (I think its called "argument expansion", but I really don't
                              know what its called, so I can't point you to docs):"

                              This works, thanks. But how acn I get rid of the ugly surrounding
                              brackets and commas?

                              e.g. If the scripts overall output was (('B', 'C'),), how to change it
                              to just B C?

                              Comment

                              Working...