print is not a function

Bengt Richter bokr at oz.net
Thu Oct 9 16:12:40 EDT 2003


On Wed, 8 Oct 2003 13:56:51 +0000 (UTC), Wojtek Walczak <gminick at hacker.pl> wrote:

>Dnia Wed, 08 Oct 2003 12:22:12 +0200, Karl Scalet napisa³(a):
>>>>>>import sys
>>>>>>sys.stdout.write("Hello world!\n")
>>
>> I came across this, but this requires an extra import sys
>> which not always is there, thanks anyhow.
>
>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)])
>
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.,

 >>> [__import__('sys').stdout.write(str(i)+'\n') for i in range(5)]
 0
 1
 2
 3
 4
 [None, None, None, None, None]
 >>> [0 for w in [__import__('sys').stdout.write] for i in range(5) if w(str(i)+'\n')]
 0
 1
 2
 3
 4
 []

You can hide the [] from the interactive result printout too:
 >>> [0 for w in [__import__('sys').stdout.write] for i in range(5) if w(str(i)+'\n')] or None
 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.,

 >>> from ut.miscutil import pl, prb
 >>> pl(map(str, range(50)), 10)

      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
 >>> prb(0xfa)
 '11111010'

Regards,
Bengt Richter




More information about the Python-list mailing list