print is not a function

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

    #16
    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.
    >[/color]
    [color=blue]
    >[ 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]

    what's wrong with the straightforward suggestion elsewhere in the thread? I.e.,

    for x in my_list: print x

    Unless you don't like the many calls to sys.stdout.writ e that are generated
    by that for loop. You can make it into a single write with

    sys.stdout.writ e('\n'.join(my_ list+['']))

    But if all your pieces already have newlines, or you just want to concatenate strings
    to stdout, note:
    [color=blue][color=green][color=darkred]
    >>> import sys
    >>> help(sys.stdout .writelines)[/color][/color][/color]
    """
    Help on built-in function writelines:

    writelines(...)
    writelines(sequ ence_of_strings ) -> None. Write the strings to the file.

    Note that newlines are not added. The sequence can be any iterable object
    producing strings. This is equivalent to calling write() for each string.
    """[color=blue][color=green][color=darkred]
    >>> sys.stdout.writ elines(['<<=starts here,\n','and this is 2nd line\n',[/color][/color][/color]
    ... '3rd - no ending newline:', '<<-missing new line\n',
    ... 'last line\n'])
    <<=starts here,
    and this is 2nd line
    3rd - no ending newline:<<-missing new line
    last line

    Regards,
    Bengt Richter

    Comment

    • Karl Scalet

      #17
      Re: print is not a function

      Bengt Richter wrote:[color=blue]
      > On Wed, 08 Oct 2003 11:32:20 +0200, Karl Scalet <news@yebu.de > wrote:
      >
      > what's wrong with the straightforward suggestion elsewhere in the thread? I.e.,
      >
      > for x in my_list: print x
      >[/color]

      I am yet convinced, this is the best solution for printing a simple list
      [color=blue]
      > Unless you don't like the many calls to sys.stdout.writ e that are generated
      > by that for loop. You can make it into a single write with
      >
      > sys.stdout.writ e('\n'.join(my_ list+['']))[/color]

      I like that as well, but as of performance wasn't the issue, the first
      solution is easier anyhow.
      [color=blue]
      >
      > But if all your pieces already have newlines, or you just want to concatenate strings
      > to stdout, note:[/color]

      Unfortunately the items in the list do not end in newlines,
      nevertheless, thanks for pointing out writelines.

      But what, if I have a condition on the list.
      Everyone tries to keep me away from list-comprehension :-)

      But I do not have a better/easier_to_type solution to

      [sys.stdout.writ e_whatsoever(x) for x in my_list if x.i_am_good_one ()]
      # x having a __str__ in that case :-)

      Maybe I do not understand potential problems from side-effects, which
      I do not see in *this* case.

      Yours insisting-ly,

      Karl

      Comment

      • Bengt Richter

        #18
        Re: print is not a function

        On Wed, 08 Oct 2003 12:27:06 GMT, Alex Martelli <aleax@aleax.it > wrote:
        [...][color=blue]
        >
        >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;-).[/color]

        Plus, the side effect to sys.modules will still happen, e.g.,:[color=blue][color=green][color=darkred]
        >>> import sys
        >>> 'math' in sys.modules[/color][/color][/color]
        False[color=blue][color=green][color=darkred]
        >>> twopi = __import__('mat h').pi*2.0
        >>> twopi[/color][/color][/color]
        6.2831853071795 862[color=blue][color=green][color=darkred]
        >>> 'math' in sys.modules[/color][/color][/color]
        True

        Anyway, with a little rearrangement, he could have his prt with most of the work built in once:
        [color=blue][color=green][color=darkred]
        >>> prt = (lambda w,x: w('%s\n'%x)).__ get__(__import_ _('sys').stdout .write)
        >>> prt('Hello');pr t('Next line')[/color][/color][/color]
        Hello
        Next line

        or a version for selected expression item side effect output:[color=blue][color=green][color=darkred]
        >>> prt = (lambda w,x: w('%s\n'%x) or x).__get__(__im port__('sys').s tdout.write)
        >>> prt('Hello'),pr t('Next line')[/color][/color][/color]
        Hello
        Next line
        ('Hello', 'Next line')[color=blue][color=green][color=darkred]
        >>> print 'expr value = %r' % (2*prt(3)*4,)[/color][/color][/color]
        3
        expr value = 24

        Hm, if that were conditional, it could have debug print use...
        [color=blue][color=green][color=darkred]
        >>> prt = (lambda w,x,p=lambda x:False: p(x) and w('<%s>'%x) and 0 or x).__get__(__im port__('sys[/color][/color][/color]
        ').stdout.write )[color=blue][color=green][color=darkred]
        >>>
        >>> pcond = lambda x: x in (2,5,11,17)
        >>>
        >>> for i in range(21): print prt(i,pcond),[/color][/color][/color]
        ...
        0 1<2>2 3 4<5>5 6 7 8 9 10<11>11 12 13 14 15 16<17>17 18 19 20

        This is getting silly with the lambdas though,
        [color=blue][color=green][color=darkred]
        >>> class Prt(object):[/color][/color][/color]
        ... wrso = __import__('sys ').stdout.write
        ... def __init__(self, pcond=lambda x:False, fmt='%s\n'):
        ... self.pcond=pcon d; self.fmt=fmt
        ... def __call__(self, x):
        ... if self.pcond(x): self.wrso(self. fmt%x)
        ... return x
        ...[color=blue][color=green][color=darkred]
        >>> prt = Prt()
        >>> for i in range(21): print prt(i),[/color][/color][/color]
        ...
        0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20[color=blue][color=green][color=darkred]
        >>> prt = Prt(pcond, '<!--\n%r discovered\n-->')
        >>> for i in range(21): print prt(i),[/color][/color][/color]
        ...
        0 1<!--
        2 discovered
        -->2 3 4<!--
        5 discovered
        -->5 6 7 8 9 10<!--
        11 discovered
        -->11 12 13 14 15 16<!--
        17 discovered
        -->17 18 19 20

        (BTW, in my other post I forgot to take into account that the OP's list of things
        to print might not all be string items).

        (Not really replying to your post, Alex, just ramblings triggered by it ;-)

        Regards,
        Bengt Richter

        Comment

        • Bengt Richter

          #19
          Re: print is not a function

          On Wed, 8 Oct 2003 13:56:51 +0000 (UTC), Wojtek Walczak <gminick@hacker .pl> wrote:
          [color=blue]
          >Dnia Wed, 08 Oct 2003 12:22:12 +0200, Karl Scalet napisa³(a):[color=green][color=darkred]
          >>>>>>import sys
          >>>>>>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]
          >
          >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)])
          >[/color]
          Not that I am advocating list comprehension abuse for other than amusement and edification,
          but you can avoid building a list of Nones and the repeated imports by rearranging things, e.g.,
          [color=blue][color=green][color=darkred]
          >>> [__import__('sys ').stdout.write (str(i)+'\n') for i in range(5)][/color][/color][/color]
          0
          1
          2
          3
          4
          [None, None, None, None, None][color=blue][color=green][color=darkred]
          >>> [0 for w in [__import__('sys ').stdout.write] for i in range(5) if w(str(i)+'\n')][/color][/color][/color]
          0
          1
          2
          3
          4
          []

          You can hide the [] from the interactive result printout too:[color=blue][color=green][color=darkred]
          >>> [0 for w in [__import__('sys ').stdout.write] for i in range(5) if w(str(i)+'\n')] or None[/color][/color][/color]
          0
          1
          2
          3
          4

          But it's kind of silly to keep typing stuff like that when you can just collect little utility
          goodies in a module and import them for interactive use, e.g.,
          [color=blue][color=green][color=darkred]
          >>> from ut.miscutil import pl, prb
          >>> pl(map(str, range(50)), 10)[/color][/color][/color]

          0 1 2 3 4 5 6 7 8 9
          10 11 12 13 14 15 16 17 18 19
          20 21 22 23 24 25 26 27 28 29
          30 31 32 33 34 35 36 37 38 39
          40 41 42 43 44 45 46 47 48 49[color=blue][color=green][color=darkred]
          >>> prb(0xfa)[/color][/color][/color]
          '11111010'

          Regards,
          Bengt Richter

          Comment

          • Bengt Richter

            #20
            Re: print is not a function

            On Wed, 08 Oct 2003 17:15:30 +0200, Karl Scalet <news@yebu.de > wrote:
            [color=blue]
            >Karl Scalet 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 ]
            >>[/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=green][color=darkred]
            > >>> print my_list[/color][/color]
            >or even[color=green][color=darkred]
            > >>> my_list[/color][/color]
            >does not give very readable results, especially if those
            >lists tend to become longer.
            >
            >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][/color]
            You don't have to, if you write (untested)

            [0 for x in locals() if x[:2]=='QA' and prt(x)] or None

            or if you make a prt that can return other than None, you can guarantee the
            if failure by writing

            [0 for x in locals() if x[:2]=='QA' and prt(x) and 0] or None[color=blue]
            >
            >In the case of doing such interactive inspections, i don't
            >mind about potential side-effects, i actually don't see them here.
            >[/color]
            Interactively, UIAM for some case, locals()==globa ls(), so if you want to
            avoid typing that more than once, you might want to make a function, e.g. (untested)

            pqa = lambda:[0 for x in globals() if x[:2]=='QA' and prt(x)] or None

            and then just type pqa()

            But a better idea is to code yourself some simple utility functions in the most
            straightforward way, with simple doc strings, and put them in a module that you can
            import from, and check on what you did, e.g., I don't always take my own advice, but
            [color=blue][color=green][color=darkred]
            >>> from ut.miscutil import pl
            >>> help(pl)[/color][/color][/color]
            Help on function pl in module ut.miscutil:

            pl(alist, cols=None, width=78)
            prints a list one left-justified item per line
            or in cols columns across width(default 78)

            For almost-throwaways relating only to a particular project, just accumulate them
            in e.g., goodies.py in the same directory, and you can interactively type

            from goodies import *

            and be ready to go.

            Regards,
            Bengt Richter

            Comment

            Working...