print is not a function
Bengt Richter
bokr at oz.net
Thu Oct 9 15:36:42 EDT 2003
On Wed, 08 Oct 2003 12:27:06 GMT, Alex Martelli <aleax at aleax.it> wrote:
[...]
>
>Right: as I said, sys.stdout.write('%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;-).
Plus, the side effect to sys.modules will still happen, e.g.,:
>>> import sys
>>> 'math' in sys.modules
False
>>> twopi = __import__('math').pi*2.0
>>> twopi
6.2831853071795862
>>> 'math' in sys.modules
True
Anyway, with a little rearrangement, he could have his prt with most of the work built in once:
>>> prt = (lambda w,x: w('%s\n'%x)).__get__(__import__('sys').stdout.write)
>>> prt('Hello');prt('Next line')
Hello
Next line
or a version for selected expression item side effect output:
>>> prt = (lambda w,x: w('%s\n'%x) or x).__get__(__import__('sys').stdout.write)
>>> prt('Hello'),prt('Next line')
Hello
Next line
('Hello', 'Next line')
>>> print 'expr value = %r' % (2*prt(3)*4,)
3
expr value = 24
Hm, if that were conditional, it could have debug print use...
>>> prt = (lambda w,x,p=lambda x:False: p(x) and w('<%s>'%x) and 0 or x).__get__(__import__('sys
').stdout.write)
>>>
>>> pcond = lambda x: x in (2,5,11,17)
>>>
>>> for i in range(21): print prt(i,pcond),
...
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,
>>> class Prt(object):
... wrso = __import__('sys').stdout.write
... def __init__(self, pcond=lambda x:False, fmt='%s\n'):
... self.pcond=pcond; self.fmt=fmt
... def __call__(self, x):
... if self.pcond(x): self.wrso(self.fmt%x)
... return x
...
>>> prt = Prt()
>>> for i in range(21): print prt(i),
...
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
>>> prt = Prt(pcond, '<!--\n%r discovered\n-->')
>>> for i in range(21): print prt(i),
...
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
More information about the Python-list
mailing list