print is not a function

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

    print is not a function

    Hi,

    quite often there is a need to just print out the items of a list.

    [ prt(x) for x in my_list ]

    that would be nice, except prt() does not exist, and print is a
    statement not a function, hence cannot replace prt as of above.

    I don't like to write d
    def prt(x):
    print x
    beforehand and any lambda construct would not be so handy.
    It should be a short one-liner.
    Any ideas?

    Karl

  • Gonçalo Rodrigues

    #2
    Re: print is not a function

    On Wed, 08 Oct 2003 11:32:20 +0200, Karl Scalet <news@yebu.de > wrote:
    [color=blue]
    >Hi,
    >
    >quite often there is a need to just print out the items of a list.
    >
    >[ prt(x) for x in my_list ]
    >
    >that would be nice, except prt() does not exist, and print is a
    >statement not a function, hence cannot replace prt as of above.
    >
    >I don't like to write d
    >def prt(x):
    > print x
    >beforehand and any lambda construct would not be so handy.
    >It should be a short one-liner.
    >Any ideas?
    >
    >Karl[/color]

    How about,
    [color=blue][color=green][color=darkred]
    >>> import sys
    >>> sys.stdout.writ e("Hello world!\n")[/color][/color][/color]
    Hello world![color=blue][color=green][color=darkred]
    >>>[/color][/color][/color]
    [color=blue][color=green][color=darkred]
    >>> help(sys)[/color][/color][/color]
    [text snipped]
    stdin -- standard input file object; used by raw_input() and
    input()
    stdout -- standard output file object; used by the print statement
    stderr -- standard error object; used for error messages
    By assigning other file objects (or objects that behave like
    files)
    to these, it is possible to redirect all of the interpreter's
    I/O.
    [text continues]

    Hope it helps, with my best regards,
    G. Rodrigues

    Comment

    • Karl Scalet

      #3
      Re: print is not a function

      Gonçalo Rodrigues wrote:
      [color=blue]
      > On Wed, 08 Oct 2003 11:32:20 +0200, Karl Scalet <news@yebu.de > wrote:
      >
      >[color=green]
      >>Hi,
      >>
      >>quite often there is a need to just print out the items of a list.
      >>
      >>[ prt(x) for x in my_list ]
      >>
      >>that would be nice, except prt() does not exist, and print is a
      >>statement not a function, hence cannot replace prt as of above.
      >>
      >>I don't like to write d
      >>def prt(x):
      >> print x
      >>beforehand and any lambda construct would not be so handy.
      >>It should be a short one-liner.
      >>Any ideas?
      >>
      >>Karl[/color]
      >
      >
      > How about,
      >
      >[color=green][color=darkred]
      >>>>import sys
      >>>>sys.stdout. write("Hello world!\n")[/color][/color][/color]

      I came across this, but this requires an extra import sys
      which not always is there, thanks anyhow.

      Karl

      Comment

      • Alex Martelli

        #4
        Re: print is not a function

        Karl Scalet wrote:
        ...[color=blue][color=green][color=darkred]
        >>>>>sys.stdout .write("Hello world!\n")[/color][/color]
        >
        > I came across this, but this requires an extra import sys
        > which not always is there, thanks anyhow.[/color]

        Ah, hadn't seen this before I answered your other post.

        Well. duplicating the print statement functionality in
        a *built-in* function to let you abuse a list comprehemsion
        for the side effects and throw away the results just ain't
        gonna happen. Built-in functions are (or should be: there
        may well be purges in Python 3.0) just for tasks so important
        and widespread that an 'import' cannot be considered.


        Alex

        Comment

        • Peter Otten

          #5
          Re: print is not a function

          Karl Scalet wrote:
          [color=blue]
          > quite often there is a need to just print out the items of a list.
          >
          > [ prt(x) for x in my_list ]
          >
          > that would be nice, except prt() does not exist, and print is a
          > statement not a function, hence cannot replace prt as of above.
          >
          > I don't like to write d
          > def prt(x):
          > print x
          > beforehand and any lambda construct would not be so handy.
          > It should be a short one-liner.
          > Any ideas?[/color]

          How about
          [color=blue][color=green][color=darkred]
          >>> myList = "alpha beta gamma".split()
          >>> print "\n".join([str(x) for x in myList])[/color][/color][/color]
          alpha
          beta
          gamma

          This way you at least put the list resulting from the comprehension to some
          use.
          General rule: use list comprehensions only if you need a list, otherwise for
          loops are both more efficient and clearer regarding the code's purpose.

          Peter

          Comment

          • Gerhard Häring

            #6
            Re: print is not a function

            Karl Scalet wrote:[color=blue]
            > Hi,
            >
            > quite often there is a need to just print out the items of a list.
            >
            > [ prt(x) for x in my_list ][/color]

            This is conceptually dubious. If prt() doesn't return anything, a list
            comprehension is useless. Functions only used as expressions shouldn't
            have side-effects, like writing to stdout.

            If you just need an a builtin function that writes to standard output,
            you can use sys.stdout.writ e().

            If you want a one-liner for your above example, something like this
            looks better to me:

            print "\n".join([str(x) for x in my_list])
            [color=blue]
            > [...] beforehand and any lambda construct would not be so handy. [...]
            > It should be a short one-liner. Any ideas?[/color]

            It appears that you're suffering from the desease of neat-looking
            one-liners.

            I'll try to cure you at the next Stammtisch (local meeting of Pythoneers
            at Munich) :-)

            I tend to agree with the Effbot's favourite lambda refactoring rule:
            http://mail.python.org/pipermail/pyt...il/036029.html ;)

            -- Gerhard

            Comment

            • Karl Scalet

              #7
              Re: print is not a function

              Alex Martelli wrote:
              [color=blue]
              > Karl Scalet wrote:
              > ...
              >[color=green][color=darkred]
              >>>>>>sys.stdou t.write("Hello world!\n")[/color]
              >>
              >>I came across this, but this requires an extra import sys
              >>which not always is there, thanks anyhow.[/color]
              >
              >
              > Ah, hadn't seen this before I answered your other post.
              >
              > Well. duplicating the print statement functionality in
              > a *built-in* function to let you abuse a list comprehemsion
              > for the side effects and throw away the results just ain't
              > gonna happen. Built-in functions are (or should be: there
              > may well be purges in Python 3.0) just for tasks so important
              > and widespread that an 'import' cannot be considered.
              >
              >
              > Alex
              >[/color]

              Thank you for the answers.
              I did not realize that taking only "the half of list comprehension"
              is a misuse of it. That would mean list comprehension always "claim"
              to be assigned to a variable. But why?
              if i *had* a function doing any meaningful with the iterated values
              by itstelf, why bother with the returned list.
              Ex:
              ignore = [ add_to_db(x) for x in my_list if x[:4]=='Hans']

              Looks at least as nice to me as

              for x in my_list:
              if x[:4]=='Hans':
              add_to_db(x)

              But there might be reasons one prefers the for loop.

              Back to my original desire:
              I of course did not request to add a new funciton to
              python built ins, I was just asking, if I miss a nice
              idea to do the trick :-)

              sys.stdout.writ e has the drawbacks:
              - need to import sys, well....
              - does no newline automatically, like print
              - only handles strings

              Again, no real pain all that :-)

              Karl

              Comment

              • Alex Martelli

                #8
                Re: print is not a function

                Karl Scalet wrote:
                ...[color=blue]
                > Thank you for the answers.[/color]

                You're welcome.
                [color=blue]
                > I did not realize that taking only "the half of list comprehension"
                > is a misuse of it. That would mean list comprehension always "claim"
                > to be assigned to a variable. But why?[/color]

                Not really: any normal use of an expression is just as fine for a
                list comprehension -- pass it as an argument, return it from a
                function, use it as part of a larger expression (e.g. concatenate
                several lists), and so on. Getting values to assigne to variables
                is just one of the many normal ways in which you can use expressions,
                and a list comprehension is an expression.

                In languages which draw a distinction between expressions and
                statements, and Python is in fact such a language, using an
                expression purely for its side effects is normally best avoided,
                because that's what statements are for. There are obvious corner
                cases (since Python does not distinguish functions, which return
                a value, from procedures, which only have side effects -- in a
                language with the expression/statement distinction, it might be
                conceptually cleaner to have the procedure/function one as well,
                as in Pascal or Fortran, but Python follows C in having the
                former but not the latter, drawing boundaries a bit differently),
                but that is a reasonable general principle.
                [color=blue]
                > if i *had* a function doing any meaningful with the iterated values
                > by itstelf, why bother with the returned list.
                > Ex:
                > ignore = [ add_to_db(x) for x in my_list if x[:4]=='Hans']
                >
                > Looks at least as nice to me as
                >
                > for x in my_list:
                > if x[:4]=='Hans':
                > add_to_db(x)
                >
                > But there might be reasons one prefers the for loop.[/color]

                You should also consider other alternatives, such as:

                for x in [ x for x in my_list if x.startswith('H ans') ]:
                add_to_db(x)

                (use .startswith, not [:4]==, for clarity & to avoid errors)
                or even lambda-based ones (preferably with itertools):

                for x in itertools.ifilt er(lambda x: x.startswith('H ans'), my_list):
                add_to_db(x)

                The reason to avoid the list-comprehension is that a LC is a
                construct that goes to quite some trouble to collect all the
                results of the expression it starts with -- creates and
                extends a list just for that, its MAIN purpose -- and when
                you DON'T CARE about the MAIN purpose of a construct, using
                it anyway is stretching things beyond clarity and legibility.

                Want another example? Another side effect of a LC (in the
                pursuit of its MAIN purpose -- creating a new list), besides
                the one of looping, is binding the loop's control variable.
                It's exceptional that way -- expressions normally don't
                bind names... but a LC does. So, people desperate for a
                close transcription of the C idiom

                while((c=nauker ())!=flip)
                blaupas(c);

                sometimes code "niceties" such as

                while [c for c in [nauker()] if c!=flip]:
                blaupas(c)

                as the LC in the while's condition binds name 'c' as well
                as giving the list (empty, i.e. false, at termination).
                Of course, in this case Python offers a direct construct
                to transliterate the idiom into:
                for c in iter(nauker, flip):
                blaupas(c)
                but it's not so smooth when nauker takes args, or when the
                form of the test is not of the "!=flip" kind.

                Anyway, the principle is the same: a LC's main purpose is
                to create a new list; therefore, use a LC when you want to
                create a new list, but not when you don't care about said
                list and only hanker for a side effect (the looping, or
                the binding of control-variable names).

                [color=blue]
                > Back to my original desire:
                > I of course did not request to add a new funciton to
                > python built ins, I was just asking, if I miss a nice
                > idea to do the trick :-)
                >
                > sys.stdout.writ e has the drawbacks:
                > - need to import sys, well....
                > - does no newline automatically, like print
                > - only handles strings
                >
                > Again, no real pain all that :-)[/color]

                Right: as I said, sys.stdout.writ e('%s\n'%x) is in fact
                the equivalent, so the newline and stringification are
                trivial issues, easily covered. If you want to avoid
                a separate import statement at all costs, well, when
                there's a will there's a way -- you CAN shoehorn it all
                into a single longish expression...:

                __import__('sys ').stdout.write ('%s\n' % x)

                whether one would WANT that, of course, is another
                issue;-).


                Alex

                Comment

                • Wojtek Walczak

                  #9
                  Re: print is not a function

                  Dnia Wed, 08 Oct 2003 12:22:12 +0200, Karl Scalet napisa³(a):[color=blue][color=green][color=darkred]
                  >>>>>import sys
                  >>>>>sys.stdout .write("Hello world!\n")[/color][/color]
                  >
                  > I came across this, but this requires an extra import sys
                  > which not always is there, thanks anyhow.[/color]

                  It's ugly, but works:
                  [__import__('sys ').stdout.write (str(i)+'\n') for i in range(5)]

                  or even:
                  [__import__('os' ).write(1, str(i)+'\n') for i in range(5)]

                  The main difference is that first will return an array of Nones
                  while the second will return an array of values returned by os.write().
                  Personally I prefer using print statement and join() method:

                  print '\n'.join([str(i) for i in range(5)])

                  --
                  [ Wojtek Walczak - gminick (at) underground.org .pl ]
                  [ <http://gminick.linuxse curity.pl/> ]
                  [ "...rozmait e zwroty, matowe od patyny dawnosci." ]

                  Comment

                  • Karl Scalet

                    #10
                    Re: print is not a function

                    Karl Scalet wrote:
                    [color=blue]
                    > Hi,
                    >
                    > quite often there is a need to just print out the items of a list.
                    >
                    > [ prt(x) for x in my_list ]
                    >[/color]
                    .....

                    Thank you all for the overwhelming sympathy to my original problem :-)

                    To clarify a bit:

                    I'm no fan of unreadable oneliners, normally, or making things more
                    complicated as they are.
                    I was just looking for the easiest way to *inspect*
                    *interactively* lists, dictionaries.
                    Evaluating such a list via[color=blue][color=green][color=darkred]
                    >>> print my_list[/color][/color][/color]
                    or even[color=blue][color=green][color=darkred]
                    >>> my_list[/color][/color][/color]
                    does not give very readable results, especially if those
                    lists tend to become longer.

                    So my own (best??) solution is:
                    [color=blue][color=green][color=darkred]
                    >>> from pprint import pprint as prt # cannot overcome this line :-(
                    >>> from qt import * # now the secret unveils
                    >>> [ prt(x) for x in locals() if x[:2]=='QA' ][/color][/color][/color]
                    # sorry Signore Alex, but it's shorter than startswith :-)
                    # gives me[color=blue][color=green][color=darkred]
                    >>> 'QAssistantClie nt'
                    >>> 'QAccel'
                    >>> 'QActionGroup
                    >>> 'QApplication'
                    >>> 'QAction'
                    >>> [None, None, None, None, None] # well, I can live with[/color][/color][/color]

                    In the case of doing such interactive inspections, i don't
                    mind about potential side-effects, i actually don't see them here.

                    Karl

                    PS:
                    I *did* write my own little helper functions for such things,
                    but then, you are in a different environment, and write the
                    helpis again and again.

                    Comment

                    • Gerrit Holl

                      #11
                      Re: print is not a function

                      Karl Scalet wrote:[color=blue]
                      > So my own (best??) solution is:
                      >[color=green][color=darkred]
                      > >>> from pprint import pprint as prt # cannot overcome this line :-(
                      > >>> from qt import * # now the secret unveils
                      > >>> [ prt(x) for x in locals() if x[:2]=='QA' ][/color][/color]
                      > # sorry Signore Alex, but it's shorter than startswith :-)
                      > # gives me[color=green][color=darkred]
                      > >>> 'QAssistantClie nt'
                      > >>> 'QAccel'
                      > >>> 'QActionGroup
                      > >>> 'QApplication'
                      > >>> 'QAction'
                      > >>> [None, None, None, None, None] # well, I can live with[/color][/color]
                      >
                      > In the case of doing such interactive inspections, i don't
                      > mind about potential side-effects, i actually don't see them here.[/color]

                      How about:

                      import qt
                      pprint.pprint(q t)

                      ?

                      Gerrit.

                      --
                      138. If a man wishes to separate from his wife who has borne him no
                      children, he shall give her the amount of her purchase money and the dowry
                      which she brought from her father's house, and let her go.
                      -- 1780 BC, Hammurabi, Code of Law
                      --
                      Asperger Syndroom - een persoonlijke benadering:

                      Kom in verzet tegen dit kabinet:
                      De website van de Socialistische Partij (SP) in Nederland: Informatie, nieuws, agenda en publicaties.


                      Comment

                      • Bruno Desthuilliers

                        #12
                        Re: print is not a function

                        Karl Scalet wrote:[color=blue]
                        > Hi,
                        >
                        > quite often there is a need to just print out the items of a list.
                        >
                        > [ prt(x) for x in my_list ]
                        >
                        > that would be nice, except prt() does not exist, and print is a
                        > statement not a function, hence cannot replace prt as of above.
                        >
                        > I don't like to write d
                        > def prt(x):
                        > print x
                        > beforehand and any lambda construct would not be so handy.
                        > It should be a short one-liner.
                        > Any ideas?[/color]

                        import sys
                        sys.stdout.writ e("hello world\n")

                        HTH

                        Comment

                        • Karl Scalet

                          #13
                          Re: print is not a function

                          Gerrit Holl wrote:
                          [color=blue]
                          > Karl Scalet wrote:
                          >[/color]
                          ....[color=blue]
                          >
                          > How about:
                          >
                          > import qt
                          > pprint.pprint(q t)
                          >
                          > ?[/color]

                          returns:
                          <module 'qt' from ....>

                          That's not the info i was for.
                          normal practice in qt-programming is[color=blue]
                          > from qt import *[/color]
                          now you can[color=blue][color=green][color=darkred]
                          >>> pprint(locals() )[/color][/color][/color]
                          as most of what's in this namespace now is
                          qt-related anyhow. But when it comes to
                          narrow down this list, as there are so
                          many items in it, I thougt using a list
                          comprehension with a condition would be
                          nice, even if I'm not longer sure after
                          all the responses :-).

                          For interactively inspecting things, I think
                          having it in one line is nice, as it's
                          easiest to recall from commandline history.

                          Which way?:[color=blue][color=green][color=darkred]
                          >>> [ pprint(x) for x in locals() if x[:3]=='QAc' ][/color][/color][/color]
                          or[color=blue][color=green][color=darkred]
                          >>> for x in locals():
                          >>> if x[:3] == 'QAc':
                          >>> print x[/color][/color][/color]

                          I cannot put this second one in a single line, so I
                          will stay with my list-comprehension-solution unless
                          I'm getting a better idea.

                          Karl

                          Comment

                          • Wolfram Kraus

                            #14
                            Re: print is not a function

                            Heyho!

                            Karl Scalet wrote:
                            [...][color=blue]
                            > For interactively inspecting things, I think
                            > having it in one line is nice, as it's
                            > easiest to recall from commandline history.
                            >
                            > Which way?:[color=green][color=darkred]
                            > >>> [ pprint(x) for x in locals() if x[:3]=='QAc' ][/color][/color]
                            > or[color=green][color=darkred]
                            > >>> for x in locals():
                            > >>> if x[:3] == 'QAc':
                            > >>> print x[/color][/color]
                            >
                            > I cannot put this second one in a single line, so I
                            > will stay with my list-comprehension-solution unless
                            > I'm getting a better idea.
                            >
                            > Karl
                            >[/color]

                            Why don't you wrap it in a function and put it in your
                            $PYTHONSTARTUP-file? That way you can call it very fast and don't need
                            to remember a one-liner.

                            Wolfram

                            Comment

                            • Karl Scalet

                              #15
                              Re: print is not a function

                              Wolfram Kraus wrote:
                              [color=blue]
                              > Heyho!
                              >
                              > Karl Scalet wrote:
                              > [...]
                              >[color=green]
                              >> For interactively inspecting things, I think
                              >> having it in one line is nice, as it's
                              >> easiest to recall from commandline history.
                              >>
                              >> Which way?:[color=darkred]
                              >> >>> [ pprint(x) for x in locals() if x[:3]=='QAc' ][/color]
                              >> or[color=darkred]
                              >> >>> for x in locals():
                              >> >>> if x[:3] == 'QAc':
                              >> >>> print x[/color]
                              >>
                              >> I cannot put this second one in a single line, so I
                              >> will stay with my list-comprehension-solution unless
                              >> I'm getting a better idea.
                              >>
                              >> Karl
                              >>[/color]
                              >
                              > Why don't you wrap it in a function and put it in your
                              > $PYTHONSTARTUP-file? That way you can call it very fast and don't need
                              > to remember a one-liner.
                              >
                              > Wolfram
                              >[/color]

                              Hello Wolfram,

                              you're right, that would be best. I myself however always end up
                              not having all the helper functions available after a while, working
                              in different environments. But that's more an organizational problem:-)

                              Thanks anyhow,
                              Karl

                              Comment

                              Working...