Re: Is there a way to globally set the print function separator?

2017-10-10 Thread Steve D'Aprano
On Tue, 10 Oct 2017 03:05 pm, John Black wrote:

>> functools.partial(print, sep='') is the winner, IMO.
> 
> Ok, I got that working too after someone told me I have to import
> functools.  Can you explain what it means?  It looks like it is not
> defining another function like the other solutions but is truly changing
> the defaults for the existing function print?

No. You are absolutely not changing the defaults for the actual built-in print
function. There is no support for that in Python.

What is happening is a bit more complex, but simplified:

- functools.partial is creating a new function-like object, almost
  identical to the built-in print in every way that matters except
  that it uses sep='';

- this special function-like object actually calls the true built-in
  print (which is why we can trust it will be almost identical);

- but you have changed the name "print" to refer to the customised
  version instead of the original.

(That change of name will only apply to the current module. Other modules will
still see the original print function.)


One way to convince yourself that this is the case is to look at the ID of the
print function before and after:


py> import functools
py> id(print)
19
py> print = functools.partial(print, sep='')
py> id(print)
20


The ID numbers are different, which proves they are different objects.

(If you try this on your computer, you will almost certainly get different ID
numbers than I did. The ID numbers are opaque integers with no inherent
meaning, and will vary according to the version of Python you have, and even
the history of what you have run in the current interpreter session.)

We can dig a little deeper, and inspect the new "print" function:

py> print.func


It is holding onto a reference to the original (which is how it can call the
original). We can confirm this:

py> id(print.func)
19


Same ID as the original.

(Note that this test is not *quite* definitive: ID numbers are only guaranteed
to be unique between objects which exist at the same time. If you delete an
object, so the garbage collector reclaims its memory and reuses it, it is
possible that the ID number may be reused as well.)



-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is there a way to globally set the print function separator?

2017-10-09 Thread John Black
In article , 
eryk...@gmail.com says...
> 
> On Mon, Oct 9, 2017 at 10:04 PM, John Black  wrote:
> > In article , python@example.invalid says...
> >>
> >> Le 09/10/2017 à 18:22, John Black a écrit :
> >> > I want sep="" to be the default without having to specify it every time I
> >> > call print.  Is that possible?
> >>
> >>  >>> oldprint = print
> >>  >>> def print(*args,**kwargs):
> >> ...   oldprint(*args,**kwargs,sep='')
> >> ...
> >>  >>> print(1,2,3)
> >> 123
> >
> > Winner!  Thanks all.
> 
> functools.partial(print, sep='') is the winner, IMO.

Ok, I got that working too after someone told me I have to import 
functools.  Can you explain what it means?  It looks like it is not 
defining another function like the other solutions but is truly changing 
the defaults for the existing function print?

John Black

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is there a way to globally set the print function separator?

2017-10-09 Thread eryk sun
On Mon, Oct 9, 2017 at 10:04 PM, John Black  wrote:
> In article , python@example.invalid says...
>>
>> Le 09/10/2017 à 18:22, John Black a écrit :
>> > I want sep="" to be the default without having to specify it every time I
>> > call print.  Is that possible?
>>
>>  >>> oldprint = print
>>  >>> def print(*args,**kwargs):
>> ...   oldprint(*args,**kwargs,sep='')
>> ...
>>  >>> print(1,2,3)
>> 123
>
> Winner!  Thanks all.

functools.partial(print, sep='') is the winner, IMO. Or even code that
use kwargs.setdefault('sep', ''). The above code is wrong in a way
that leads to a TypeError. Can you see the problem?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is there a way to globally set the print function separator?

2017-10-09 Thread Grant Edwards
On 2017-10-09, John Black  wrote:

> I want to make sure I understand what this line is doing: 
>
>> oldprint = print
>
> Experimenting, I find this is not a rename because I can use both 
> function names.

Right it's not _changing_ a name.  It's _adding_ a name.

> It looks it literally copies the function "print" to 
> another function called "oldprint".

No, it binds a new name of 'oldprint' to the function to which 'print'
is bound.  It does not create a second function, nor does it remove
the binding of the name 'print' to that function.  It just adds a
second name that's also bound to that function.

> But now, I have a way to modify the builtin funciton "print" by
> referencing oldprint.  Without oldprint, I have no way to directly
> modify print?

Well... you can still access the builtin print via the module that
contains it:

   >>> def print(*args, **kw):
   ...   __builtins__.print(*args, sep='', **kw)
   ... 
   >>> print(1,2,3)

However, anytime you find yourself using double underscore stuff you
should think to yourself "I should find a better way to do that."

> def print(*args, **kw):
> print(*args, sep='', **kw)
>
> meaning print calls print (itself) with sep=''.  But this failed and I 
> guess the reason is that it would keep calling itself recursively adding 
> sep='' each time?

Yep.

Just define a new function with a new name:

   def myprint(*args, **kw):
   print(*args, sep='', **kw)

Redefining builtins is just going get you sworn at down the road a
bit.  If not by yourself, then by somebody else...

-- 
Grant Edwards   grant.b.edwardsYow! Used staples are good
  at   with SOY SAUCE!
  gmail.com

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is there a way to globally set the print function separator?

2017-10-09 Thread John Black
In article , python@example.invalid says...
> 
> Le 09/10/2017 à 18:22, John Black a écrit :
> > I want sep="" to be the default without having to specify it every time I
> > call print.  Is that possible?
> 
>  >>> oldprint = print
>  >>> def print(*args,**kwargs):
> ...   oldprint(*args,**kwargs,sep='')
> ...
>  >>> print(1,2,3)
> 123

Winner!  Thanks all.

I want to make sure I understand what this line is doing: 

> oldprint = print

Experimenting, I find this is not a rename because I can use both 
function names.  It looks it literally copies the function "print" to 
another function called "oldprint".  But now, I have a way to modify the 
builtin funciton "print" by referencing oldprint.  Without oldprint, I 
have no way to directly modify print?  For example, based on your post, I 
tried:

def print(*args, **kw):
print(*args, sep='', **kw)

meaning print calls print (itself) with sep=''.  But this failed and I 
guess the reason is that it would keep calling itself recursively adding 
sep='' each time?  Thanks.

John Black
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is there a way to globally set the print function separator?

2017-10-09 Thread Chris Angelico
On Tue, Oct 10, 2017 at 7:40 AM, John Black  wrote:
> In article ,
> __pete...@web.de says...
>>
>> John Black wrote:
>>
>> > I want sep="" to be the default without having to specify it every time I
>> > call print.  Is that possible?
>>
>> No, but you can replace the print function with your own:
>>
>> >>> print = functools.partial(print, sep="")
>> >>> print("I", "recommend", "you", "choose", "another", "name", "and",
>> "preserve", "your", "sanity")
>> Irecommendyouchooseanothernameandpreserveyoursanity
>>
>> And everybody else's.
>
> print=functools.partial(print, sep="")
> NameError: name 'functools' is not defined

It's a module you can import.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is there a way to globally set the print function separator?

2017-10-09 Thread John Black
In article , 
__pete...@web.de says...
> 
> John Black wrote:
> 
> > I want sep="" to be the default without having to specify it every time I
> > call print.  Is that possible?
> 
> No, but you can replace the print function with your own:
> 
> >>> print = functools.partial(print, sep="")
> >>> print("I", "recommend", "you", "choose", "another", "name", "and", 
> "preserve", "your", "sanity")
> Irecommendyouchooseanothernameandpreserveyoursanity
> 
> And everybody else's.

print=functools.partial(print, sep="")
NameError: name 'functools' is not defined

John Black
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is there a way to globally set the print function separator?

2017-10-09 Thread Terry Reedy

On 10/9/2017 12:22 PM, John Black wrote:

I want sep="" to be the default without having to specify it every time I
call print.  Is that possible?

John Black


Define a replacement print function that makes this the default. 
Something like (untested, a detail may be wrong):


_print = print
def print(*args, **kwargs):
_print(*args, {'sep':''}.update(kwargs))


--
Terry Jan Reedy

--
https://mail.python.org/mailman/listinfo/python-list


Re: Is there a way to globally set the print function separator?

2017-10-09 Thread Peter Otten
John Black wrote:

> I want sep="" to be the default without having to specify it every time I
> call print.  Is that possible?

No, but you can replace the print function with your own:

>>> print = functools.partial(print, sep="")
>>> print("I", "recommend", "you", "choose", "another", "name", "and", 
"preserve", "your", "sanity")
Irecommendyouchooseanothernameandpreserveyoursanity

And everybody else's.

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is there a way to globally set the print function separator?

2017-10-09 Thread Python

Le 09/10/2017 à 18:22, John Black a écrit :

I want sep="" to be the default without having to specify it every time I
call print.  Is that possible?


>>> oldprint = print
>>> def print(*args,**kwargs):
...   oldprint(*args,**kwargs,sep='')
...
>>> print(1,2,3)
123
--
https://mail.python.org/mailman/listinfo/python-list


Re: Is there a way to globally set the print function separator?

2017-10-09 Thread Paul Moore
On 9 October 2017 at 17:22, John Black  wrote:
> I want sep="" to be the default without having to specify it every time I
> call print.  Is that possible?

def myprint(*args, **kw):
print(*args, sep="", **kw)

If you want, assign print=myprint.

Paul
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is there a way to globally set the print function separator?

2017-10-09 Thread Ned Batchelder

On 10/9/17 12:22 PM, John Black wrote:

I want sep="" to be the default without having to specify it every time I
call print.  Is that possible?




There isn't a way to change the default for print(sep="") globally. 
Generally when you want better control over the output, you use string 
formatting.  Instead of:


    print("X is ", x, " and y is ", y, sep="")

use:

    print("X is {} and y is {}".format(x, y))

If you show us your actual print lines, we can give more concrete advice.

--Ned.
--
https://mail.python.org/mailman/listinfo/python-list


Is there a way to globally set the print function separator?

2017-10-09 Thread John Black
I want sep="" to be the default without having to specify it every time I 
call print.  Is that possible?

John Black

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Need help for the print() function with a better order

2016-10-03 Thread breamoreboy
On Sunday, October 2, 2016 at 2:12:39 AM UTC+1, 38016...@gmail.com wrote:
> I am trying to print a simple decision tree for my homework.
> The answer must keep in this format:
> 
> Top 7,4,0.95
> career gain = 100
>   1.Management 2, 3, 0.9709505944546686
>   2.Service 5, 1, 0.6500224216483541
> location gain = 100
>   1.Oregon 4, 1, 0.7219280948873623
>   2.California 3, 3, 1.0
> edu_level gain = 100
>   1.High School 5, 1, 0.6500224216483541
>   2.College 2, 3, 0.9709505944546686
> years_exp gain = 100
>   1.Less than 3 3, 1, 0.8112781244591328
>   2.3 to 10 2, 1, 0.9182958340544896
>   3.More than 10 2, 2, 1.0
> 
> Here is my code:
> features={'edu_level':['High School','College'],'career':
> ['Management','Service'],'years_exp':['Less than 3','3 to 10','More than 
> 10'],'location':['Oregon','California']}
> 
> print('Top 7,4,0.95')
> for key in features:
> print('{} gain = {}'.format(key,100))
> attributes_list=features[key]
> kargs={}
> for i in range(len(attributes_list)):
> kargs[key]=attributes_list[i]
> low=table.count('Low',**kargs)
> high=table.count('High',**kargs)
> print('\t{}.{} {}, {}, 
> {}'.format(i+1,attributes_list[i],low,high,entropy(low,high)))
> 
> I set all the gain as 100 now.But actually the gain must calculate with the 
> data below.
> For example, the career gain need the data of 'Management' and 'Service'.
> I don't know how to do.
> or Anyone can provide me a better logic?

This code cannot run as neither count nor entropy are defined.

You can loop around the features like this:-

for key, attributes_list in features.items():

'iteritems' as suggested by Peter Pearson is Python 2 only.

You can loop around your attributes with:-

for attribute in attributes_list:

If you need the index in the loop use the enumerate function 
https://docs.python.org/3/library/functions.html#enumerate

Kindest regards.

Mark Lawrence.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Need help for the print() function with a better order

2016-10-02 Thread 380162267qq
在 2016年10月2日星期日 UTC-4下午1:05:58,Peter Pearson写道:
> On Sat, 1 Oct 2016 18:12:29 -0700 (PDT), 38016226...@gmail.com wrote:
> > I am trying to print a simple decision tree for my homework.
> > The answer must keep in this format:
> >
> > Top 7,4,0.95
> > career gain = 100
> > 1.Management 2, 3, 0.9709505944546686
> > 2.Service 5, 1, 0.6500224216483541
> > location gain = 100
> > 1.Oregon 4, 1, 0.7219280948873623
> > 2.California 3, 3, 1.0
> > edu_level gain = 100
> > 1.High School 5, 1, 0.6500224216483541
> > 2.College 2, 3, 0.9709505944546686
> > years_exp gain = 100
> > 1.Less than 3 3, 1, 0.8112781244591328
> > 2.3 to 10 2, 1, 0.9182958340544896
> > 3.More than 10 2, 2, 1.0
> >
> > Here is my code:
> > features={'edu_level':['High School',
>  'College'],
> 'career':['Management',
>   'Service'],
> 'years_exp':['Less than 3',
>  '3 to 10',
>  'More than 10'],
> 'location':['Oregon',
> 'California']}
> >
> > print('Top 7,4,0.95')
> > for key in features:
> > print('{} gain = {}'.format(key,100))
> > attributes_list=features[key]
> > kargs={}
> > for i in range(len(attributes_list)):
> > kargs[key]=attributes_list[i]
> > low=table.count('Low',**kargs)
> > high=table.count('High',**kargs)
> > print('\t{}.{} {}, {}, {}'.format(
> i+1,attributes_list[i],low,high,entropy(low,high)))
> >
> > I set all the gain as 100 now.But actually the gain must calculate
> > with the data below.  For example, the career gain need the data of
> > 'Management' and 'Service'.  I don't know how to do.  or Anyone can
> > provide me a better logic?
> 
> I interpret your question as meaning that the value that you 
> print after "gain =" should depend on features[key].  To do that,
> you'll need to insert a line resembling
>   gain = gain_from_features(features[key])
> before the print statement.  You'll have to write the gain_from_features
> function, and provide it with the numbers from which it will
> compute the gain.
> 
> As a stylistic suggestion, note that Python allows you to break
> your "features=" line into a more readable format, as I have done
> above.
> 
> Another stylistic suggestions:
>   for key, attributes_list in features.iteritems():
> 
> -- 
> To email me, substitute nowhere->runbox, invalid->com.

Thank you for your suggestion.I was so tired last night printing the structure 
of decision tree crushed me.
I am not familiar with python and now I will try to modify my code.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Need help for the print() function with a better order

2016-10-02 Thread Peter Pearson
On Sat, 1 Oct 2016 18:12:29 -0700 (PDT), 38016226...@gmail.com wrote:
> I am trying to print a simple decision tree for my homework.
> The answer must keep in this format:
>
> Top 7,4,0.95
> career gain = 100
>   1.Management 2, 3, 0.9709505944546686
>   2.Service 5, 1, 0.6500224216483541
> location gain = 100
>   1.Oregon 4, 1, 0.7219280948873623
>   2.California 3, 3, 1.0
> edu_level gain = 100
>   1.High School 5, 1, 0.6500224216483541
>   2.College 2, 3, 0.9709505944546686
> years_exp gain = 100
>   1.Less than 3 3, 1, 0.8112781244591328
>   2.3 to 10 2, 1, 0.9182958340544896
>   3.More than 10 2, 2, 1.0
>
> Here is my code:
> features={'edu_level':['High School',
 'College'],
'career':['Management',
  'Service'],
'years_exp':['Less than 3',
 '3 to 10',
 'More than 10'],
'location':['Oregon',
'California']}
>
> print('Top 7,4,0.95')
> for key in features:
> print('{} gain = {}'.format(key,100))
> attributes_list=features[key]
> kargs={}
> for i in range(len(attributes_list)):
> kargs[key]=attributes_list[i]
> low=table.count('Low',**kargs)
> high=table.count('High',**kargs)
> print('\t{}.{} {}, {}, {}'.format(
i+1,attributes_list[i],low,high,entropy(low,high)))
>
> I set all the gain as 100 now.But actually the gain must calculate
> with the data below.  For example, the career gain need the data of
> 'Management' and 'Service'.  I don't know how to do.  or Anyone can
> provide me a better logic?

I interpret your question as meaning that the value that you 
print after "gain =" should depend on features[key].  To do that,
you'll need to insert a line resembling
  gain = gain_from_features(features[key])
before the print statement.  You'll have to write the gain_from_features
function, and provide it with the numbers from which it will
compute the gain.

As a stylistic suggestion, note that Python allows you to break
your "features=" line into a more readable format, as I have done
above.

Another stylistic suggestions:
  for key, attributes_list in features.iteritems():

-- 
To email me, substitute nowhere->runbox, invalid->com.
-- 
https://mail.python.org/mailman/listinfo/python-list


Need help for the print() function with a better order

2016-10-01 Thread 380162267qq
I am trying to print a simple decision tree for my homework.
The answer must keep in this format:

Top 7,4,0.95
career gain = 100
1.Management 2, 3, 0.9709505944546686
2.Service 5, 1, 0.6500224216483541
location gain = 100
1.Oregon 4, 1, 0.7219280948873623
2.California 3, 3, 1.0
edu_level gain = 100
1.High School 5, 1, 0.6500224216483541
2.College 2, 3, 0.9709505944546686
years_exp gain = 100
1.Less than 3 3, 1, 0.8112781244591328
2.3 to 10 2, 1, 0.9182958340544896
3.More than 10 2, 2, 1.0

Here is my code:
features={'edu_level':['High School','College'],'career':
['Management','Service'],'years_exp':['Less than 3','3 to 10','More than 
10'],'location':['Oregon','California']}

print('Top 7,4,0.95')
for key in features:
print('{} gain = {}'.format(key,100))
attributes_list=features[key]
kargs={}
for i in range(len(attributes_list)):
kargs[key]=attributes_list[i]
low=table.count('Low',**kargs)
high=table.count('High',**kargs)
print('\t{}.{} {}, {}, 
{}'.format(i+1,attributes_list[i],low,high,entropy(low,high)))





I set all the gain as 100 now.But actually the gain must calculate with the 
data below.
For example, the career gain need the data of 'Management' and 'Service'.
I don't know how to do.
or Anyone can provide me a better logic?



-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Print function not working

2016-08-11 Thread Michael Selik
On Thu, Aug 11, 2016 at 1:38 PM MRAB  wrote:

> On 2016-08-11 18:18, Chris Angelico wrote:
> > On Fri, Aug 12, 2016 at 3:03 AM, Atri Mahapatra
> >  wrote:
> >> I have installed IDLE 3.5.1 and wrote the following  to check if print
> is working. When it runs, I do not see anything is printed:
> >>
> >> class Base: #{
> >> def __init__( self ): #{
> >> print("Hello, world: \n\n");
> >>
> >> #}
> >>
> >> #}
> >>
> >>
> >> if ( __name__ == " __main__"): #{
> >> root = Base();
> >> #}
> >>
> >> Can anyone please point out the reason?
> >>
> >> Thanks,
> >> Atri
> >
> > Is name equal to main? That is, are you running this code as a top-level
> script?
> >
> It's not checking whether the name is "__main__", but whether it's "
> __main__" (note the space after the first quote).
>
> > Also: You do not need to write Python code as if it were C or Java.
> > All that extra punctuation is just putting unnecessary stress on the
> > world's punctuation mines, which are already overworked. :)
> >
> +1
>

When debugging something like this, one technique is to remove bits of code
to reduce the complexity. Remove something, run the code, check the
results, then repeat if it's still failing.

If you're not sure how class initializers work, maybe convert to a regular
function and try again.

def foo():
print('hello')
if __name__ == '__main__':
foo()

If that still doesn't work, maybe get rid of the function.

if __name__ == '__main__':
print('hello')

And if that still doesn't work, maybe get rid of the if-statement.

print('hello')

I think you'll find that the single line program "print('hello')" works
just fine.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Print function not working

2016-08-11 Thread MRAB

On 2016-08-11 18:18, Chris Angelico wrote:

On Fri, Aug 12, 2016 at 3:03 AM, Atri Mahapatra
 wrote:

I have installed IDLE 3.5.1 and wrote the following  to check if print is 
working. When it runs, I do not see anything is printed:

class Base: #{
def __init__( self ): #{
print("Hello, world: \n\n");

#}

#}


if ( __name__ == " __main__"): #{
root = Base();
#}

Can anyone please point out the reason?

Thanks,
Atri


Is name equal to main? That is, are you running this code as a top-level script?

It's not checking whether the name is "__main__", but whether it's " 
__main__" (note the space after the first quote).



Also: You do not need to write Python code as if it were C or Java.
All that extra punctuation is just putting unnecessary stress on the
world's punctuation mines, which are already overworked. :)


+1

--
https://mail.python.org/mailman/listinfo/python-list


Re: Print function not working

2016-08-11 Thread Peter Otten
Atri Mahapatra wrote:

> I have installed IDLE 3.5.1 and wrote the following  to check if print is
> working. When it runs, I do not see anything is printed:
> 
> class Base: #{
> def __init__( self ): #{
> print("Hello, world: \n\n");
> 
> #}
> 
> #}
> 
> 
> if ( __name__ == " __main__"): #{
> root = Base();
> #}
> 
> Can anyone please point out the reason?

Hard to tell. Either there slipped an extra space into the string literal in

> if ( __name__ == " __main__"): #{

or the interpreter got really annoyed about you trying to write C/Java/PHP 
rather than proper Python...

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Print function not working

2016-08-11 Thread Chris Angelico
On Fri, Aug 12, 2016 at 3:03 AM, Atri Mahapatra
 wrote:
> I have installed IDLE 3.5.1 and wrote the following  to check if print is 
> working. When it runs, I do not see anything is printed:
>
> class Base: #{
> def __init__( self ): #{
> print("Hello, world: \n\n");
>
> #}
>
> #}
>
>
> if ( __name__ == " __main__"): #{
> root = Base();
> #}
>
> Can anyone please point out the reason?
>
> Thanks,
> Atri

Is name equal to main? That is, are you running this code as a top-level script?

Also: You do not need to write Python code as if it were C or Java.
All that extra punctuation is just putting unnecessary stress on the
world's punctuation mines, which are already overworked. :)

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Print function not working

2016-08-11 Thread Atri Mahapatra
I have installed IDLE 3.5.1 and wrote the following print command to see if it 
is working. When I ran the code nothing is printed. Can you please point the 
reason- anything wrong with the code?



class Base: #{
def __init__( self ): #{
print("Hello, world: \n\n");

#}

#}


if ( __name__ == " __main__"): #{
root = Base();
#}

Thanks,
Atri
-- 
https://mail.python.org/mailman/listinfo/python-list


Print function not working

2016-08-11 Thread Atri Mahapatra
I have installed IDLE 3.5.1 and wrote the following  to check if print is 
working. When it runs, I do not see anything is printed:

class Base: #{
def __init__( self ): #{
print("Hello, world: \n\n");

#}

#}


if ( __name__ == " __main__"): #{
root = Base();
#}

Can anyone please point out the reason?

Thanks,
Atri
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: print() function with encoding= and errors= parameters?

2016-08-03 Thread Malcolm Greene
> You could use win_unicode_console enabled in sitecustomize or usercustomize.
> https://pypi.python.org/pypi/win_unicode_console

The pypi link you shared has an excellent summary of the issues
associated when working Unicode from the Windows terminal.

Thank you Eryk.

Malcolm
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: print() function with encoding= and errors= parameters?

2016-08-03 Thread eryk sun
On Wed, Aug 3, 2016 at 3:35 PM, Malcolm Greene  wrote:
> But under Windows, the stdout is workstation specific and *never* UTF-8. So 
> the
> occasional non-ASCII string trips up our diagnostic output when tested under
> Windows.

You could use win_unicode_console enabled in sitecustomize or usercustomize.

https://pypi.python.org/pypi/win_unicode_console
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: print() function with encoding= and errors= parameters?

2016-08-03 Thread Malcolm Greene
Chris,

> Don't forget that the print function can simply be shadowed.

I did forget! Another excellent option. Thank you!

Malcolm
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: print() function with encoding= and errors= parameters?

2016-08-03 Thread Chris Angelico
On Thu, Aug 4, 2016 at 1:35 AM, Malcolm Greene  wrote:
> My use case was diagnostic output being (temporarily) output to stdout
> via debug related print statements. The output is for debugging only and
> not meant for production. I was looking for a solution that would allow
> me to output to the console with as few changes to the original scripts
> as possible, eg. non-invasive except for the print statements
> themselves.

Don't forget that the print function can simply be shadowed. If you
have a lot of code that uses print(...) to output text, and you want
to quickly transform it so it uses ASCII + backslash-replace, you
could simply:

def print(msg):
sys.stdout.write(msg.encode("ASCII",
errors="backslashreplace").decode("ASCII") + "\n")

or whatever other transformation you want. Your current situation may
be solved, but this is a great tool in your toolbox, and worth bearing
in mind.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: print() function with encoding= and errors= parameters?

2016-08-03 Thread Malcolm Greene
Thank you Random832 and Peter - excellent ideas.

My use case was diagnostic output being (temporarily) output to stdout
via debug related print statements. The output is for debugging only and
not meant for production. I was looking for a solution that would allow
me to output to the console with as few changes to the original scripts
as possible, eg. non-invasive except for the print statements
themselves.

When debugging under Linux/OSX, standard print statements work fine
because their stdouts' encoding is UTF-8. But under Windows, the stdout
is workstation specific and *never* UTF-8. So the occasional non-ASCII
string trips up our diagnostic output when tested under Windows.

Peter's suggestion to set the PYTHONIOENCODING [1] environment variable
is the non-invasive, diagnostic only, non-production solution I was
looking for ... for the use case at hand. 

Again, thank you both.

Malcolm

[1] PYTHONIOENCODING=ascii:backslashreplace
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: print() function with encoding= and errors= parameters?

2016-08-03 Thread Random832
On Wed, Aug 3, 2016, at 11:09, Peter Otten wrote:
> I'm unsure about this myself -- wouldn't it be better to detach the 
> underlying raw stream? Like

Well, "better" depends on your point of view.

> The ValueError raised if you try to write to the original stdout
> looks like a feature to me.

Maybe. But if the goal is to not cause problems for other code that
consumes the original stdio, this is very much not a feature.

Of course, it's hard to imagine in what kind of program design it is
reasonable for there not to be a single guiding principle controlling
all of the code that sends output to stdout, but I'm not the one asking
the question here.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: print() function with encoding= and errors= parameters?

2016-08-03 Thread Peter Otten
Random832 wrote:

> On Wed, Aug 3, 2016, at 08:29, Malcolm Greene wrote:
>> Looking for a way to use the Python 3 print() function with encoding and
>> errors parameters.

>> Are there any concerns with closing and re-opening sys.stdout so
>> sys.stdout has a specific encoding and errors behavior? Would this break
>> other standard libraries that depend on sys.stdout being configured a
>> specific way?

Can you give an example of what you have in mind? One that would not be 
considered a bug in said library?

> You could duplicate stdout [open(os.dup(sys.stdout.fileno()), ...)]
> 
> You could make an IO class which sends bytes output to sys.stdout.buffer
> but won't close it when closed (you know, it'd be nice to be able to
> have "not owned underlying stream" as an option of the standard IO
> classes)
> 
> If your output isn't going to be long, you could print everything to a
> StringIO and then write to sys.stdout.buffer at the end.

I'm unsure about this myself -- wouldn't it be better to detach the 
underlying raw stream? Like

>>> import sys, io
>>> print("ähnlich üblich möglich")
ähnlich üblich möglich
>>> sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding="ascii", 
errors="xmlcharrefreplace")
>>> print("ähnlich üblich möglich")
ähnlich üblich möglich

The ValueError raised if you try to write to the original stdout

>>> print("ähnlich üblich möglich", file=sys.__stdout__)
Traceback (most recent call last):
  File "", line 1, in 
ValueError: underlying buffer has been detached

looks like a feature to me.

PS: An alternative would be to set the environment variable:

$ PYTHONIOENCODING=ascii:backslashreplace python3 -c 'print("Smørrebrød")'
Sm\xf8rrebr\xf8d


-- 
https://mail.python.org/mailman/listinfo/python-list


Re: print() function with encoding= and errors= parameters?

2016-08-03 Thread Random832
On Wed, Aug 3, 2016, at 08:29, Malcolm Greene wrote:
> Looking for a way to use the Python 3 print() function with encoding and
> errors parameters.
> 
> Are there any concerns with closing and re-opening sys.stdout so
> sys.stdout has a specific encoding and errors behavior? Would this break
> other standard libraries that depend on sys.stdout being configured a
> specific way?

You could duplicate stdout [open(os.dup(sys.stdout.fileno()), ...)]

You could make an IO class which sends bytes output to sys.stdout.buffer
but won't close it when closed (you know, it'd be nice to be able to
have "not owned underlying stream" as an option of the standard IO
classes)

If your output isn't going to be long, you could print everything to a
StringIO and then write to sys.stdout.buffer at the end.
-- 
https://mail.python.org/mailman/listinfo/python-list


print() function with encoding= and errors= parameters?

2016-08-03 Thread Malcolm Greene
Looking for a way to use the Python 3 print() function with encoding and
errors parameters.

Are there any concerns with closing and re-opening sys.stdout so
sys.stdout has a specific encoding and errors behavior? Would this break
other standard libraries that depend on sys.stdout being configured a
specific way?

Thank you,
Malcolm
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I don't read docs and don't know how to use Google. What does the print function do?

2014-11-14 Thread Chris Angelico
On Fri, Nov 14, 2014 at 9:58 PM, Steven D'Aprano
 wrote:
> http://blog.codinghorror.com/why-cant-programmers-program/
>
> Not everyone agrees that this is a thing:
>
> http://www.skorks.com/2010/10/99-out-of-100-programmers-cant-program-i-call-bullshit/
>
> I'm inclined to accept that maybe 99 out of 100 *applications* for
> programming jobs are from people who can't program, but I don't think that
> 99 out of 100 *programmers* can't program. It's probably more like 65,
> maybe 70 out of 100, tops.

I was talking only about *applications* at that point. From the point
of view of an applicant, the massive noise of incompetent people
trying to get the job means it's really hard to get heard, especially
since a lot of the incompetents can make their resumes look great. [1]
So getting a job you apply for based on your own skill is... not easy.
At least, I'm fairly sure it's not easy. All I know is that it's never
happened to me.

[1] They probably learned from all the other department heads.
http://dilbert.com/strips/comic/2011-02-20/

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I don't read docs and don't know how to use Google. What does the print function do?

2014-11-14 Thread Steven D'Aprano
Chris Angelico wrote:

> There are blog posts out there about how large proportions of
> applicants can't even write simple code on command... and I've taken
> the questions and shown them to my siblings (who protest that they're
> definitely not programmers), proving that a basic smattering of
> mathematical nous puts you above people who are trying to earn money
> from coding.
> 
> It's like a carpenter, looking for a skilled assistant, and getting
> people who don't know which end of a saw to hold.

http://blog.codinghorror.com/why-cant-programmers-program/

Not everyone agrees that this is a thing:

http://www.skorks.com/2010/10/99-out-of-100-programmers-cant-program-i-call-bullshit/

I'm inclined to accept that maybe 99 out of 100 *applications* for
programming jobs are from people who can't program, but I don't think that
99 out of 100 *programmers* can't program. It's probably more like 65,
maybe 70 out of 100, tops.

Ha ha only serious.

More here:

http://www.protocolostomy.com/2010/03/15/programmers-that-cant-program/




-- 
Steven

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I don't read docs and don't know how to use Google. What does the print function do?

2014-11-13 Thread giacomo boffi
"Clayton Kirkwood"  writes:

> Although I suspect for a price you could bring all of your
> professional programming jobs to somebody here, but I think you
> would pay out more than you would make.

s/ here/ else/ and your assumption can be falsified
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I don't read docs and don't know how to use Google. What does the print function do?

2014-11-12 Thread Chris Angelico
On Wed, Nov 12, 2014 at 4:39 PM, Clayton Kirkwood  wrote:
> Chris, you're kidding, right? People get programming jobs without the
> knowledge? How do they keep them? Don't hiring people look at code examples,
> or previous employment? Ask relevant questions?

Oh, I didn't say they *keep* the jobs, nor necessarily even get them!
(Although that can happen too - check out http://thedailywtf.com/ and
some of the stories of what former employees' code can look like.) I'm
talking about them applying, and then the potential employers have to
weed through the utter incompetents to find the few who actually know
what they're talking about. If the employer is himself/herself a
programmer, this is a huge waste of a skilled person's time; if not,
the short-listing of applicants will be highly flawed. Hence the
problem: it's so hard to pick the right applicants that the right
applicants end up not being picked - and so jobs remain unfilled (as I
can attest to - the same job postings keep coming up in my RSS feeds),
or incompetents get jobs and then get moved on.

Sure, you could figure out whether one person is worth hiring or not.
But when you have two hundred applications, can you afford to talk to
every single one of them? I doubt it. And that's the problem.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


RE: I don't read docs and don't know how to use Google. What does the print function do?

2014-11-12 Thread Clayton Kirkwood


>-Original Message-
>From: Python-list [mailto:python-list-
>bounces+crk=godblessthe...@python.org] On Behalf Of Chris Angelico
>Sent: Tuesday, November 11, 2014 12:36 AM
>Cc: python-list@python.org
>Subject: Re: I don't read docs and don't know how to use Google. What
>does the print function do?
>
>On Tue, Nov 11, 2014 at 10:21 AM, Clayton Kirkwood 
>wrote:
>> Uh, how are you going to maintain a programming job if you don't know
>> how to program? I don't want to act but I know Brad Pitt makes lots of
>> money doing it, so I want to be Brad Pitt. Not! Not going to happen.
>> Although I suspect for a price you could bring all of your
>> professional programming jobs to somebody here, but I think you would
>pay out more than you would make.
>>
>
>I'm not entirely sure how it works, but it does happen. I've been
>writing code for over two decades, and trying to earn a living at it for
>one and a bit, and in all that time, I have *never even once* found a
>job by applying in the classic way and sending in a resume.
>There are blog posts out there about how large proportions of applicants
>can't even write simple code on command... and I've taken the questions
>and shown them to my siblings (who protest that they're definitely not
>programmers), proving that a basic smattering of mathematical nous puts
>you above people who are trying to earn money from coding.
>
>It's like a carpenter, looking for a skilled assistant, and getting
>people who don't know which end of a saw to hold.
>
>It's like a prospective accountant not knowing the words "credit" and
>"debit".
>
>It's like someone trying to rule a country just on the basis of looking
>good on television... okay, so maybe there's one other "industry" where
>the incompetent have a shot at it.
>
>But fortunately, it's not everyone. There are the "bad eggs" who waste
>everyone's time, but there are plenty of truly competent people too.
>It's just a matter of figuring out which are the "will-be-competent"
>and which are the "totally lazy and not going anywhere", and there's not
>always a lot to distinguish them by.
>
>ChrisA

Chris, you're kidding, right? People get programming jobs without the
knowledge? How do they keep them? Don't hiring people look at code examples,
or previous employment? Ask relevant questions? My wife works for the county
district attorney's office, and she tells me a lot about the incompetence of
her co-workers and how they just kind of don't do their job, the petty
personalities. My daughter works for AAA and tells how little co-workers
know and are not willing to learn anything, but expect raises, etc. It's
really hard for me to believe. I've worked in professional environs like
Intel and Lockheed. You didn't keep a job long if you screwed around, and
except for one person, everyone worked hard and earned their living,
learning as much as they could, and generally got along. Some were great
work groups that were incredibly rewarding and enjoyable. I have trouble
believing the work ethics and behavior my family tells me about. Totally
foreign to me.

Clayton
>--
>https://mail.python.org/mailman/listinfo/python-list



-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I don't read docs and don't know how to use Google. What does the print function do?

2014-11-11 Thread alister
On Mon, 10 Nov 2014 21:36:54 +, Denis McMahon wrote:

> On Mon, 10 Nov 2014 10:56:18 -0800, sohcahtoa82 wrote:
> 
>> ... I know software engineers make lots of money so I want to be one.
> 
> I hear that pretty boy male escorts can make even more money than
> software engineers.
> 
> They also don't need to learn how to program, which is something
> software engineers do need to do, so it sounds as if you'd be better off
> signing up with an escort agency.

in both cases you start at the bottom, as a rent boy you stay there



-- 
He thinks by infection, catching an opinion like a cold.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I don't read docs and don't know how to use Google. What does the print function do?

2014-11-11 Thread Chris Angelico
On Tue, Nov 11, 2014 at 10:21 AM, Clayton Kirkwood  wrote:
> Uh, how are you going to maintain a programming job if you don't know how to
> program? I don't want to act but I know Brad Pitt makes lots of money doing
> it, so I want to be Brad Pitt. Not! Not going to happen. Although I suspect
> for a price you could bring all of your professional programming jobs to
> somebody here, but I think you would pay out more than you would make.
>

I'm not entirely sure how it works, but it does happen. I've been
writing code for over two decades, and trying to earn a living at it
for one and a bit, and in all that time, I have *never even once*
found a job by applying in the classic way and sending in a resume.
There are blog posts out there about how large proportions of
applicants can't even write simple code on command... and I've taken
the questions and shown them to my siblings (who protest that they're
definitely not programmers), proving that a basic smattering of
mathematical nous puts you above people who are trying to earn money
from coding.

It's like a carpenter, looking for a skilled assistant, and getting
people who don't know which end of a saw to hold.

It's like a prospective accountant not knowing the words "credit" and "debit".

It's like someone trying to rule a country just on the basis of
looking good on television... okay, so maybe there's one other
"industry" where the incompetent have a shot at it.

But fortunately, it's not everyone. There are the "bad eggs" who waste
everyone's time, but there are plenty of truly competent people too.
It's just a matter of figuring out which are the "will-be-competent"
and which are the "totally lazy and not going anywhere", and there's
not always a lot to distinguish them by.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


RE: I don't read docs and don't know how to use Google. What does the print function do?

2014-11-11 Thread Clayton Kirkwood


>-Original Message-
>From: Python-list [mailto:python-list-
>bounces+crk=godblessthe...@python.org] On Behalf Of Grant Edwards
>Sent: Monday, November 10, 2014 1:01 PM
>To: python-list@python.org
>Subject: Re: I don't read docs and don't know how to use Google. What
>does the print function do?
>
>On 2014-11-10, sohcahto...@gmail.com  wrote:
>
>> Please help me this assignment is due in an hour.  Don't give me
>> hints, just give me the answer because I only want a grade.  I'm not
>> actually interested in learning how to program, but I know software
>> engineers make lots of money so I want to be one.
>
>That's the saddest troll I've seen in ages.

Uh, how are you going to maintain a programming job if you don't know how to
program? I don't want to act but I know Brad Pitt makes lots of money doing
it, so I want to be Brad Pitt. Not! Not going to happen. Although I suspect
for a price you could bring all of your professional programming jobs to
somebody here, but I think you would pay out more than you would make.

Clayton
>
>--
>Grant Edwards   grant.b.edwardsYow! I just forgot my
>whole
>  at   philosophy of life!!!
>  gmail.com
>--
>https://mail.python.org/mailman/listinfo/python-list



-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I don't read docs and don't know how to use Google. What does the print function do?

2014-11-11 Thread Manolo Martínez
On 11/10/14 at 09:00pm, Grant Edwards wrote:
> That's the saddest troll I've seen in ages.

That, on the other hand, is a pretty decent bit of trolling.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I don't read docs and don't know how to use Google. What does the print function do?

2014-11-10 Thread MRAB

On 2014-11-10 20:16, Ethan Furman wrote:

On 11/10/2014 11:59 AM, Larry Martell wrote:

On Mon, Nov 10, 2014 at 2:49 PM, Roy Smith  wrote:

In article ,
  sohcahto...@gmail.com wrote:


Please help me this assignment is due in an hour.  Don't give me hints, just
give me the answer because I only want a grade.  I'm not actually interested
in learning how to program, but I know software engineers make lots of money
so I want to be one.


This post is a sine of the times.


Don't go off on a tangent.


Please!  We don't need all this hyperbole!


... cos it's off-topic.

--
https://mail.python.org/mailman/listinfo/python-list


Re: I don't read docs and don't know how to use Google. What does the print function do?

2014-11-10 Thread Ian Kelly
On Mon, Nov 10, 2014 at 2:45 PM,   wrote:
> On Monday, November 10, 2014 1:01:05 PM UTC-8, Grant Edwards wrote:
>> On 2014-11-10, sohcahtoa82  wrote:
>>
>> > Please help me this assignment is due in an hour.  Don't give me
>> > hints, just give me the answer because I only want a grade.  I'm not
>> > actually interested in learning how to program, but I know software
>> > engineers make lots of money so I want to be one.
>>
>> That's the saddest troll I've seen in ages.
>>
>
> Either you and I have a different definition of what a troll is, or your 
> ability to detect parody and recognize a joke is a bit off.

The former, probably. It may have been amusing, but it was nonetheless
an off-topic post seeking to get a reaction, i.e. a troll.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I don't read docs and don't know how to use Google. What does the print function do?

2014-11-10 Thread sohcahtoa82
On Monday, November 10, 2014 1:01:05 PM UTC-8, Grant Edwards wrote:
> On 2014-11-10, sohcahtoa82  wrote:
> 
> > Please help me this assignment is due in an hour.  Don't give me
> > hints, just give me the answer because I only want a grade.  I'm not
> > actually interested in learning how to program, but I know software
> > engineers make lots of money so I want to be one.
> 
> That's the saddest troll I've seen in ages.
> 

Either you and I have a different definition of what a troll is, or your 
ability to detect parody and recognize a joke is a bit off.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I don't read docs and don't know how to use Google. What does the print function do?

2014-11-10 Thread Denis McMahon
On Mon, 10 Nov 2014 10:56:18 -0800, sohcahtoa82 wrote:

> ... I know software engineers
> make lots of money so I want to be one.

I hear that pretty boy male escorts can make even more money than 
software engineers.

They also don't need to learn how to program, which is something software 
engineers do need to do, so it sounds as if you'd be better off signing 
up with an escort agency.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I don't read docs and don't know how to use Google. What does the print function do?

2014-11-10 Thread Grant Edwards
On 2014-11-10, sohcahto...@gmail.com  wrote:

> Please help me this assignment is due in an hour.  Don't give me
> hints, just give me the answer because I only want a grade.  I'm not
> actually interested in learning how to program, but I know software
> engineers make lots of money so I want to be one.

That's the saddest troll I've seen in ages.

-- 
Grant Edwards   grant.b.edwardsYow! I just forgot my whole
  at   philosophy of life!!!
  gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I don't read docs and don't know how to use Google. What does the print function do?

2014-11-10 Thread Ethan Furman

On 11/10/2014 11:59 AM, Larry Martell wrote:

On Mon, Nov 10, 2014 at 2:49 PM, Roy Smith  wrote:

In article ,
  sohcahto...@gmail.com wrote:


Please help me this assignment is due in an hour.  Don't give me hints, just
give me the answer because I only want a grade.  I'm not actually interested
in learning how to program, but I know software engineers make lots of money
so I want to be one.


This post is a sine of the times.


Don't go off on a tangent.


Please!  We don't need all this hyperbole!

--
~Ethan~
--
https://mail.python.org/mailman/listinfo/python-list


Re: I don't read docs and don't know how to use Google. What does the print function do?

2014-11-10 Thread Mark Lawrence

On 10/11/2014 19:24, Peter Otten wrote:

sohcahto...@gmail.com wrote:


Please help me this assignment is due in an hour.  Don't give me hints,
just give me the answer because I only want a grade.  I'm not actually
interested in learning how to program, but I know software engineers make
lots of money so I want to be one.


I'm sorry I have to decline your kind offer unless you also let me do your
dishes and walk your dog.



Quote Of The Day/Week/Month/Year/Decade/Millenium*

* please delete whichever you feel is appropriate

--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

--
https://mail.python.org/mailman/listinfo/python-list


Re: I don't read docs and don't know how to use Google. What does the print function do?

2014-11-10 Thread Larry Martell
On Mon, Nov 10, 2014 at 2:49 PM, Roy Smith  wrote:
> In article ,
>  sohcahto...@gmail.com wrote:
>
>> Please help me this assignment is due in an hour.  Don't give me hints, just
>> give me the answer because I only want a grade.  I'm not actually interested
>> in learning how to program, but I know software engineers make lots of money
>> so I want to be one.
>
> This post is a sine of the times.

Don't go off on a tangent.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I don't read docs and don't know how to use Google. What does the print function do?

2014-11-10 Thread Roy Smith
In article ,
 sohcahto...@gmail.com wrote:

> Please help me this assignment is due in an hour.  Don't give me hints, just 
> give me the answer because I only want a grade.  I'm not actually interested 
> in learning how to program, but I know software engineers make lots of money 
> so I want to be one.

This post is a sine of the times.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I don't read docs and don't know how to use Google. What does the print function do?

2014-11-10 Thread Peter Otten
sohcahto...@gmail.com wrote:

> Please help me this assignment is due in an hour.  Don't give me hints,
> just give me the answer because I only want a grade.  I'm not actually
> interested in learning how to program, but I know software engineers make
> lots of money so I want to be one.

I'm sorry I have to decline your kind offer unless you also let me do your 
dishes and walk your dog.

-- 
https://mail.python.org/mailman/listinfo/python-list


I don't read docs and don't know how to use Google. What does the print function do?

2014-11-10 Thread sohcahtoa82
Please help me this assignment is due in an hour.  Don't give me hints, just 
give me the answer because I only want a grade.  I'm not actually interested in 
learning how to program, but I know software engineers make lots of money so I 
want to be one.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: print function and unwanted trailing space

2013-09-12 Thread Albert Hopkins


On Wed, Sep 11, 2013, at 07:36 AM, Wayne Werner wrote:
> On Sat, 31 Aug 2013, candide wrote:
> > # -
> > for i in range(5):
> >print(i, end=' ')   # <- The last ' ' is unwanted
> > print()
> > # -
> 
> Then why not define end='' instead?

I think the OP meant that ' ' is wanted up until the final item.. so
something like

for i in range(4):
print(i, end=' ')
print(4)

or, better:
print(' '.join(str(i) for i in range(5)))
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: print function and unwanted trailing space

2013-09-11 Thread Wayne Werner

On Sat, 31 Aug 2013, candide wrote:

# -
for i in range(5):
   print(i, end=' ')   # <- The last ' ' is unwanted
print()
# -


Then why not define end='' instead?

-W
--
https://mail.python.org/mailman/listinfo/python-list


Re: print function and unwanted trailing space

2013-08-31 Thread Terry Reedy

On 8/31/2013 7:15 PM, Joshua Landau wrote:

On 31 August 2013 23:08, Chris Angelico  wrote:

On Sun, Sep 1, 2013 at 1:43 AM, Oscar Benjamin
 wrote:

On 31 August 2013 16:30, Chris Angelico  wrote:


but doesn't solve all the cases (imagine a string or an iterator).


Similar but maybe simpler, and copes with more arbitrary iterables:

it=iter(range(5))
print(next(it), end='')
for i in it:
 print('',i, end='')


If you want to work with arbitrary iterables then you'll want

it = iter(iterable)
try:
 val = next(it)
except StopIteration:
 pass  # Or raise or something?
else:
 print(val, end='')
for i in it:
 print('', i, end='')


I went with this version:

except StopIteration:
 raise

In other words, if it's going to bomb, let it bomb :)


I think the point is that StopIteration is an unsafe error to raise.


It should only be raised by iterator.__next__ method and caught by 
iterator user and not re-raised. Raise something like "ValueError('empty 
iterable') from None" instead.



--
Terry Jan Reedy

--
http://mail.python.org/mailman/listinfo/python-list


Re: print function and unwanted trailing space

2013-08-31 Thread Joshua Landau
On 31 August 2013 23:08, Chris Angelico  wrote:
> On Sun, Sep 1, 2013 at 1:43 AM, Oscar Benjamin
>  wrote:
>> On 31 August 2013 16:30, Chris Angelico  wrote:

 but doesn't solve all the cases (imagine a string or an iterator).
>>>
>>> Similar but maybe simpler, and copes with more arbitrary iterables:
>>>
>>> it=iter(range(5))
>>> print(next(it), end='')
>>> for i in it:
>>> print('',i, end='')
>>
>> If you want to work with arbitrary iterables then you'll want
>>
>> it = iter(iterable)
>> try:
>> val = next(it)
>> except StopIteration:
>> pass  # Or raise or something?
>> else:
>> print(val, end='')
>> for i in it:
>> print('', i, end='')
>
> I went with this version:
>
> except StopIteration:
> raise
>
> In other words, if it's going to bomb, let it bomb :)

I think the point is that StopIteration is an unsafe error to raise.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: print function and unwanted trailing space

2013-08-31 Thread Chris Angelico
On Sun, Sep 1, 2013 at 1:43 AM, Oscar Benjamin
 wrote:
> On 31 August 2013 16:30, Chris Angelico  wrote:
>>>
>>> but doesn't solve all the cases (imagine a string or an iterator).
>>
>> Similar but maybe simpler, and copes with more arbitrary iterables:
>>
>> it=iter(range(5))
>> print(next(it), end='')
>> for i in it:
>> print('',i, end='')
>
> If you want to work with arbitrary iterables then you'll want
>
> it = iter(iterable)
> try:
> val = next(it)
> except StopIteration:
> pass  # Or raise or something?
> else:
> print(val, end='')
> for i in it:
> print('', i, end='')

I went with this version:

except StopIteration:
raise

In other words, if it's going to bomb, let it bomb :)

ChrisA
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: print function and unwanted trailing space

2013-08-31 Thread candide

Le 31/08/2013 15:59, Peter Otten a écrit :




To make it crystal clear, the above was to illustrate the algorithm used in
Python 2, not a suggestion.



Ok sorry, I misinterpreted.




> I still think you should live with a trailing space


Are you sure ? The following code

#--
import io

output = io.StringIO()
n=5
for i in range(n-1):
print(i, end=' ', file=output)
print(n-1, file=output)
print(output.getvalue().count(' '))
#--


outputs 4, the correct number of space character.



> or go with my actual
> suggestion
>
> print(*range(5))
>


It's a very good suggestion (the best one in fact) but rather 
complicated to explain to pure novices in programming.


--
http://mail.python.org/mailman/listinfo/python-list


Re: print function and unwanted trailing space

2013-08-31 Thread candide

Le 31/08/2013 12:31, Peter Otten a écrit :


with `softspace` saved as a file attribute, is gone in Python3.



After reading

http://docs.python.org/3.0/whatsnew/3.0.html#print-is-a-function


I understand what you meant by "softspace". Thanks.

--
http://mail.python.org/mailman/listinfo/python-list


Re: print function and unwanted trailing space

2013-08-31 Thread Oscar Benjamin
On 31 August 2013 16:30, Chris Angelico  wrote:
>>
>> but doesn't solve all the cases (imagine a string or an iterator).
>
> Similar but maybe simpler, and copes with more arbitrary iterables:
>
> it=iter(range(5))
> print(next(it), end='')
> for i in it:
> print('',i, end='')

If you want to work with arbitrary iterables then you'll want

it = iter(iterable)
try:
val = next(it)
except StopIteration:
pass  # Or raise or something?
else:
print(val, end='')
for i in it:
print('', i, end='')


Oscar
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: print function and unwanted trailing space

2013-08-31 Thread Chris Angelico
On Sat, Aug 31, 2013 at 11:33 PM, candide  wrote:
> The if instruction imposes useless testing (we know in advance the problem
> to occur at the very end of the loop) and useless writing (writing '').
>
> The following is clearer
>
> # -
> n=5
> for i in range(n-1):
> print(i, end=' ')
> print(n-1)
> # -
>
>
> but doesn't solve all the cases (imagine a string or an iterator).

Similar but maybe simpler, and copes with more arbitrary iterables:

it=iter(range(5))
print(next(it), end='')
for i in it:
print('',i, end='')

Also guarantees to use 'sep' between the elements, fwiw.

ChrisA
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: print function and unwanted trailing space

2013-08-31 Thread Steven D'Aprano
On Sat, 31 Aug 2013 14:59:17 +0200, candide wrote:

> Le 31/08/2013 13:16, Steven D'Aprano a écrit :
> 
> 
>> Of course it does. Have you actually tried it?
> 
> 
> Of course I did, redirecting the output to a file in order to spot an
> eventually trailing space. I did the same for the Python 3 code.


Fair enough. Seems like the print statement implementation in Python 2 is 
uglier than I imagined, keeping hidden state between invocations.



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: print function and unwanted trailing space

2013-08-31 Thread Peter Otten
candide wrote:

> Le 31/08/2013 12:31, Peter Otten a écrit :
>  > softspace = False
>  > for i in range(5):
>  >  if softspace:
>  >  print(end=" ")
>  >  print(i, end="")
>  >  softspace = True
>  > print()
> 
> 
> The if instruction imposes useless testing (we know in advance the
> problem to occur at the very end of the loop) and useless writing
> (writing '').

To make it crystal clear, the above was to illustrate the algorithm used in 
Python 2, not a suggestion. Python 2 uses that "useless testing" -- which is 
cheap compared to actual I/O.

> The following is clearer
> 
> # -
> n=5
> for i in range(n-1):
>  print(i, end=' ')
> print(n-1)
> # -
> 
> 
> but doesn't solve all the cases (imagine a string or an iterator).

I still think you should live with a trailing space or go with my actual 
suggestion

print(*range(5))

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: print function and unwanted trailing space

2013-08-31 Thread candide

Le 31/08/2013 13:24, Ned Batchelder a écrit :


For a beginner course, the trailing space is fine, use this code.


I was really expecting there was a trick but I'll follow your advice, 
after all the trailing space is invisible!


Nevertheless, this can be quite annoying. For instance, some automated 
program testing (cf. http://www.spoj.com/, http://acm.timus.ru/, etc) 
expect the exact output to get accepted, no byte more or a byte less.






--
http://mail.python.org/mailman/listinfo/python-list


Re: print function and unwanted trailing space

2013-08-31 Thread candide

Le 31/08/2013 12:31, Peter Otten a écrit :
> softspace = False
> for i in range(5):
>  if softspace:
>  print(end=" ")
>  print(i, end="")
>  softspace = True
> print()


The if instruction imposes useless testing (we know in advance the 
problem to occur at the very end of the loop) and useless writing 
(writing '').


The following is clearer

# -
n=5
for i in range(n-1):
print(i, end=' ')
print(n-1)
# -


but doesn't solve all the cases (imagine a string or an iterator).
--
http://mail.python.org/mailman/listinfo/python-list


Re: print function and unwanted trailing space

2013-08-31 Thread candide

Le 31/08/2013 13:16, Steven D'Aprano a écrit :



Of course it does. Have you actually tried it?



Of course I did, redirecting the output to a file in order to spot an 
eventually trailing space. I did the same for the Python 3 code.

--
http://mail.python.org/mailman/listinfo/python-list


Re: print function and unwanted trailing space

2013-08-31 Thread Oscar Benjamin
On 31 August 2013 12:16, Steven D'Aprano
 wrote:
> On Sat, 31 Aug 2013 10:17:23 +0200, candide wrote:
>
>> What is the equivalent in Python 3 to the following Python 2 code:
>>
>> # -
>> for i in range(5):
>>  print i,
>> # -
>>
>> ?
>>
>> Be careful that the above code doesn't add a trailing space after the
>> last number in the list,
>
> Of course it does. Have you actually tried it? The interactive
> interpreter is tricky, because you cannot directly follow a for-loop with
> another statement. If you try, the interactive interpreter gives you an
> indentation error. But we can work around it by sticking everything
> inside an if block, like so:
>
> py> if True:
> ... for i in range(5):
> ... print i,
> ... # could be pages of code here
> ... print "FINISHED"
> ...
> 0 1 2 3 4 FINISHED

The space is added by the final print statement, not the last one in
the loop. Here's a demo that shows this:

$ cat print.py
for i in range(5):
print i,
print
$ cat print3.py
for i in range(5):
print(i, end=' ')
print()
$ py -2.7 print.py | cat -A
0 1 2 3 4^M$
$ py -3.3 print3.py | cat -A
0 1 2 3 4 ^M$

(Notice the space between the 4 and ^M (which is cat's way of saying '\r').

[snip]
>
>> hence the following Python 3 code isn't strictly equivalent:
>>
>>
>> # -
>> for i in range(5):
>>  print(i, end=' ')   # <- The last ' ' is unwanted
>> print()
>
> The last space is exactly the same as you get in Python 2. But really,
> who cares about an extra invisible space? In non-interactive mode, the
> two are exactly the same (ignoring the extra print() call outside the
> loop), but even at the interactive interpreter, I'd like to see the code
> where an extra space makes a real difference.

I seem to remember it breaking some unit test or doc test something
when I first tried to port something using 2to3 (this is the
replacement that 2to3 uses for print with a trailing comma). It's not
so important for interactive terminal output but when you do 'python
script.py > output.dat' the unwanted space shouldn't be there. The
soft-space feature is useful but stateful as Peter says and defies the
normal concept of what happens when calling a function so it was
removed when print became a function.


Oscar
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: print function and unwanted trailing space

2013-08-31 Thread Peter Otten
Steven D'Aprano wrote:

> On Sat, 31 Aug 2013 10:17:23 +0200, candide wrote:
> 
>> What is the equivalent in Python 3 to the following Python 2 code:
>> 
>> # -
>> for i in range(5):
>>  print i,
>> # -
>> 
>> ?
>> 
>> Be careful that the above code doesn't add a trailing space after the
>> last number in the list,
> 
> Of course it does. Have you actually tried it? The interactive
> interpreter is tricky, because you cannot directly follow a for-loop with
> another statement. If you try, the interactive interpreter gives you an
> indentation error. But we can work around it by sticking everything
> inside an if block, like so:
> 
> py> if True:
> ... for i in range(5):
> ... print i,
> ... # could be pages of code here
> ... print "FINISHED"
> ...
> 0 1 2 3 4 FINISHED
> 
> 
> Or you could stick the code inside an exec, which doesn't have the same
> limitation as the interactive interpreter. This mimics the behaviour of
> code in a file:
> 
> py> exec """for i in range(5):
> ... print i,
> ... print "FINISHED"
> ... """
> 0 1 2 3 4 FINISHED
> 
> 
> The same results occur with any other Python 2.x, and indeed all the way
> back to Python 1.5 and older.

Your test is flawed. The softspace mechanism ensures that there is a space 
*between* all printed items, but not *after* the last printed item.

print "FINISHED"

will add a space while

print

will not. Compare:

>>> with open("tmp.txt", "w") as f:
... for i in range(3): print >> f, i,
... print >> f
... 
>>> open("tmp.txt").read()
'0 1 2\n'
>>> with open("tmp.txt", "w") as f:
... for i in range(3): print >> f, i,
... print >> f, "FINISHED"
... 
>>> open("tmp.txt").read()
'0 1 2 FINISHED\n'




-- 
http://mail.python.org/mailman/listinfo/python-list


Re: print function and unwanted trailing space

2013-08-31 Thread Ned Batchelder

On 8/31/13 4:17 AM, candide wrote:


What is the equivalent in Python 3 to the following Python 2 code:

# -
for i in range(5):
print i,
# -

?

Be careful that the above code doesn't add a trailing space after the 
last number in the list, hence the following Python 3 code isn't 
strictly equivalent:



# -
for i in range(5):
print(i, end=' ')   # <- The last ' ' is unwanted
print()
# -


For a beginner course, the trailing space is fine, use this code. 
They'll never notice the trailing space (I wouldn't have!) and to 
explain why the comma leaves off the last one takes a really advanced 
understanding of obscure details anyway.


--Ned.
--
http://mail.python.org/mailman/listinfo/python-list


Re: print function and unwanted trailing space

2013-08-31 Thread Steven D'Aprano
On Sat, 31 Aug 2013 10:17:23 +0200, candide wrote:

> What is the equivalent in Python 3 to the following Python 2 code:
> 
> # -
> for i in range(5):
>  print i,
> # -
> 
> ?
> 
> Be careful that the above code doesn't add a trailing space after the
> last number in the list, 

Of course it does. Have you actually tried it? The interactive 
interpreter is tricky, because you cannot directly follow a for-loop with 
another statement. If you try, the interactive interpreter gives you an 
indentation error. But we can work around it by sticking everything 
inside an if block, like so:

py> if True:
... for i in range(5):
... print i,
... # could be pages of code here
... print "FINISHED"
...
0 1 2 3 4 FINISHED


Or you could stick the code inside an exec, which doesn't have the same 
limitation as the interactive interpreter. This mimics the behaviour of 
code in a file:

py> exec """for i in range(5):
... print i,
... print "FINISHED"
... """
0 1 2 3 4 FINISHED


The same results occur with any other Python 2.x, and indeed all the way 
back to Python 1.5 and older.


> hence the following Python 3 code isn't strictly equivalent:
> 
> 
> # -
> for i in range(5):
>  print(i, end=' ')   # <- The last ' ' is unwanted
> print()


The last space is exactly the same as you get in Python 2. But really, 
who cares about an extra invisible space? In non-interactive mode, the 
two are exactly the same (ignoring the extra print() call outside the 
loop), but even at the interactive interpreter, I'd like to see the code 
where an extra space makes a real difference.



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: print function and unwanted trailing space

2013-08-31 Thread Peter Otten
candide wrote:

> Le 31/08/2013 10:43, Andreas Perstinger a écrit :
> 
>  > How about
>  >
>  >  >>> print(" ".join(str(i) for i in range(5)))
>  > 0 1 2 3 4
>  >
> 
> 
> Thanks for your answer. The output is stricly the same but the code
> doesn't suit my needs :
> 
> 1) I'm porting to Python 3 a Python 2 full beginner course : the
> learners are not aware of the join method nor the str type nor
> generators stuff;
> 2) Your code introduce a (sometimes) useless conversion to str (consider
> a string instead of range(5)).

You are out of luck, the softspace mechanism, roughly

softspace = False
for i in range(5):
if softspace:
print(end=" ")
print(i, end="")
softspace = True
print()

with `softspace` saved as a file attribute, is gone in Python3. But I don't 
think that someone who doesn't know it existed will miss the feature.

Maybe you can allow for /some/ magic and introduce your students to

print(*range(5))

early-on.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: print function and unwanted trailing space

2013-08-31 Thread candide

Le 31/08/2013 10:43, Andreas Perstinger a écrit :

> How about
>
>  >>> print(" ".join(str(i) for i in range(5)))
> 0 1 2 3 4
>


Thanks for your answer. The output is stricly the same but the code 
doesn't suit my needs :


1) I'm porting to Python 3 a Python 2 full beginner course : the 
learners are not aware of the join method nor the str type nor 
generators stuff;
2) Your code introduce a (sometimes) useless conversion to str (consider 
a string instead of range(5)).



--
http://mail.python.org/mailman/listinfo/python-list


Re: print function and unwanted trailing space

2013-08-31 Thread Andreas Perstinger

On 31.08.2013 10:17, candide wrote:


What is the equivalent in Python 3 to the following Python 2 code:

# -
for i in range(5):
  print i,
# -

?


How about

>>> print(" ".join(str(i) for i in range(5)))
0 1 2 3 4

Bye, Andreas



--
http://mail.python.org/mailman/listinfo/python-list


print function and unwanted trailing space

2013-08-31 Thread candide


What is the equivalent in Python 3 to the following Python 2 code:

# -
for i in range(5):
print i,
# -

?

Be careful that the above code doesn't add a trailing space after the 
last number in the list, hence the following Python 3 code isn't 
strictly equivalent:



# -
for i in range(5):
print(i, end=' ')   # <- The last ' ' is unwanted
print()
# -
--
http://mail.python.org/mailman/listinfo/python-list


Re: Print Function

2012-09-22 Thread Walter Hurry
On Sat, 22 Sep 2012 01:26:43 +, Steven D'Aprano wrote:

> On Fri, 21 Sep 2012 13:20:09 -0700, gengyangcai wrote:
> 
>> I am currently using Python 3.2.3 . WHen I use the print function by
>> typing print "Game Over" , it mentions  " SyntaxError : invalid syntax
>> ".  Any ideas on what the problem is and how to resolve it  ?
> 
> No, none what so ever. Perhaps you are the first person in the world to
> have come across this error. If you ever solve it, please write up the
> solution and put it on a blog or a website somewhere so that if it ever
> happens again, googling for "python print SyntaxError" will return a
> useful result.
> 
> Tongue-firmly-in-cheek-ly y'rs,

I think OP rather gave the game away with the subject line.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Print Function

2012-09-22 Thread Mark Lawrence

On 22/09/2012 02:26, Steven D'Aprano wrote:

On Fri, 21 Sep 2012 13:20:09 -0700, gengyangcai wrote:


I am currently using Python 3.2.3 . WHen I use the print function by
typing print "Game Over" , it mentions  " SyntaxError : invalid syntax
".  Any ideas on what the problem is and how to resolve it  ?


No, none what so ever. Perhaps you are the first person in the world to
have come across this error. If you ever solve it, please write up the
solution and put it on a blog or a website somewhere so that if it ever
happens again, googling for "python print SyntaxError" will return a
useful result.

Tongue-firmly-in-cheek-ly y'rs,




+ one trillion

--
Cheers.

Mark Lawrence.

--
http://mail.python.org/mailman/listinfo/python-list


Re: Print Function

2012-09-21 Thread Steven D'Aprano
On Fri, 21 Sep 2012 13:20:09 -0700, gengyangcai wrote:

> I am currently using Python 3.2.3 . WHen I use the print function by
> typing print "Game Over" , it mentions  " SyntaxError : invalid syntax
> ".  Any ideas on what the problem is and how to resolve it  ?

No, none what so ever. Perhaps you are the first person in the world to 
have come across this error. If you ever solve it, please write up the 
solution and put it on a blog or a website somewhere so that if it ever 
happens again, googling for "python print SyntaxError" will return a 
useful result.

Tongue-firmly-in-cheek-ly y'rs,


-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Print Function

2012-09-21 Thread Ian Kelly
On Fri, Sep 21, 2012 at 3:11 PM, Alister  wrote:
> On Fri, 21 Sep 2012 14:54:14 -0600, Ian Kelly wrote:
>
>> On Fri, Sep 21, 2012 at 2:28 PM, Rodrick Brown 
>> wrote:
>>> Go away troll!
>>
>> Troll? It looked like a sincere question to me.
>
> but one that page 1 of the documentation would answer.

So point the asker to the documentation, don't just dismiss them as a troll.

This newsgroup has a reputation for being friendly.  Let's keep it that way.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Print Function

2012-09-21 Thread John Gordon
In  
gengyang...@gmail.com writes:

> I am currently using Python 3.2.3 . WHen I use the print function by
> typing print "Game Over" , it mentions  " SyntaxError : invalid syntax ".
> Any ideas on what the problem is and how to resolve it  ? Thanks a lot .

In python version 3, print was changed into a function.

Use this and it will work:

  print("Game Over")

-- 
John Gordon   A is for Amy, who fell down the stairs
gor...@panix.com  B is for Basil, assaulted by bears
-- Edward Gorey, "The Gashlycrumb Tinies"

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Print Function

2012-09-21 Thread Alister
On Fri, 21 Sep 2012 14:54:14 -0600, Ian Kelly wrote:

> On Fri, Sep 21, 2012 at 2:28 PM, Rodrick Brown 
> wrote:
>> Go away troll!
> 
> Troll? It looked like a sincere question to me.

but one that page 1 of the documentation would answer.



-- 
Waste not, get your budget cut next year.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Print Function

2012-09-21 Thread Ian Kelly
On Fri, Sep 21, 2012 at 2:28 PM, Rodrick Brown  wrote:
> Go away troll!

Troll? It looked like a sincere question to me.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Print Function

2012-09-21 Thread Rodrick Brown
Go away troll!

Sent from my iPhone

On Sep 21, 2012, at 4:27 PM, "gengyang...@gmail.com"
 wrote:

> Hello ,
>
>
> I am currently using Python 3.2.3 . WHen I use the print function by typing 
> print "Game Over" , it mentions  " SyntaxError : invalid syntax ".  Any ideas 
> on what the problem is and how to resolve it  ? Thanks a lot .
>
>
> GengYang
> --
> http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Print Function

2012-09-21 Thread Tarek Ziadé

On 9/21/12 10:20 PM, gengyang...@gmail.com wrote:

Hello ,


I am currently using Python 3.2.3 . WHen I use the print function by typing print "Game 
Over" , it mentions  " SyntaxError : invalid syntax ".  Any ideas on what the 
problem is and how to resolve it  ? Thanks a lot .


print was a statement in python 2.x, it is now a function so you need 
parenthesis:


>>> print("Game Over")
Game Over




GengYang


--
http://mail.python.org/mailman/listinfo/python-list


Print Function

2012-09-21 Thread gengyangcai
Hello ,


I am currently using Python 3.2.3 . WHen I use the print function by typing 
print "Game Over" , it mentions  " SyntaxError : invalid syntax ".  Any ideas 
on what the problem is and how to resolve it  ? Thanks a lot .


GengYang
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Globally override built-in print function?

2010-04-16 Thread J. Cliff Dyer
On Fri, 2010-04-16 at 09:50 -0700, Dave W. wrote:
> >>> old_print = __builtins__.print
> >>> __builtins__.print = printhook
> >>> yield
> >>> __builtins__.print = old_print
> >
> >> I'm pretty sure this is semantically equivalent to my original
> >> code, but I gave it a try anyway.
> >
> > Not at all. Declaring "global print" then assigning to "print"
> > simply changes what the module's "print" variable refers to. Other
> > modules are unaffected.  "Global" variables aren't truly global;
> > they are actually local to the module.  You need to replace it in
> > the __builtins__ because that's where everyone else gets it.
> >
> > > FWIW, it doesn't work, either. :-}
> >
> > Right. Lie answered why. I didn't pay attention and thought you
> > were already using Python 3.
> 
> Thanks, Robert and Lie for the considered and informative responses.
> Getting feedback like this from people who really understand
> Python's internals is invaluable.  Sounds like redirecting
> stdout/stderr is the way to go.  (Especially given that they're not
> the 'real' stdout/stderr---that was news to me!)
> 
> [xref "Suppress output to stdout/stderr in InteractiveInterpreter"]

It's good to remember that names in python are just names.  The objects
that have the names "sys.stdout" and "sys.stderr" are the real deal, but
when you assign a file object to them, you are not actually
"redirecting" anything.  You are assigning a name (sys.stdout) to a
different file object.  The old object still points to STDOUT, but
sys.stdout no longer refers to that object as long as your assignment
remains in scope.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Globally override built-in print function?

2010-04-16 Thread Dave W.
>>> old_print = __builtins__.print
>>> __builtins__.print = printhook
>>> yield
>>> __builtins__.print = old_print
>
>> I'm pretty sure this is semantically equivalent to my original
>> code, but I gave it a try anyway.
>
> Not at all. Declaring "global print" then assigning to "print"
> simply changes what the module's "print" variable refers to. Other
> modules are unaffected.  "Global" variables aren't truly global;
> they are actually local to the module.  You need to replace it in
> the __builtins__ because that's where everyone else gets it.
>
> > FWIW, it doesn't work, either. :-}
>
> Right. Lie answered why. I didn't pay attention and thought you
> were already using Python 3.

Thanks, Robert and Lie for the considered and informative responses.
Getting feedback like this from people who really understand
Python's internals is invaluable.  Sounds like redirecting
stdout/stderr is the way to go.  (Especially given that they're not
the 'real' stdout/stderr---that was news to me!)

[xref "Suppress output to stdout/stderr in InteractiveInterpreter"]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Globally override built-in print function?

2010-04-16 Thread Robert Kern

On 2010-04-15 21:17 PM, Dave W. wrote:

I naively thought I could capture output from exec()'ed print
invocations by (somehow) overriding 'print' globally.  But this
seems not to be possible.




old_print = __builtins__.print
__builtins__.print = printhook
yield
__builtins__.print = old_print


I'm pretty sure this is semantically equivalent to my original code,
but I gave it a try anyway.


Not at all. Declaring "global print" then assigning to "print" simply changes 
what the module's "print" variable refers to. Other modules are unaffected. 
"Global" variables aren't truly global; they are actually local to the module. 
You need to replace it in the __builtins__ because that's where everyone else 
gets it.



FWIW, it doesn't work, either. :-}


Right. Lie answered why. I didn't pay attention and thought you were already 
using Python 3.


--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

--
http://mail.python.org/mailman/listinfo/python-list


Re: Globally override built-in print function?

2010-04-16 Thread Lie Ryan
On 04/16/10 12:17, Dave W. wrote:
>>> I naively thought I could capture output from exec()'ed print
>>> invocations by (somehow) overriding 'print' globally.  But this
>>> seems not to be possible.  
> 
>>
>>old_print = __builtins__.print
>>__builtins__.print = printhook
>>yield
>>__builtins__.print = old_print
> 
> I'm pretty sure this is semantically equivalent to my original code,
> but I gave it a try anyway.  FWIW, it doesn't work, either. :-}
> 
>> But you really should replace sys.stdout and sys.stderr instead.
> 
> I'm starting to believe it, but... I thought that one of the
> benefits of making print a function was that it *could* be globally
> replaced. So far I've had no luck injecting a custom print
> replacement into other modules.  Is this really not possible?

No, the benefit of 'from __future__ import print_function' is for easing
transition to python 3. The ability to replace print globally only works
in python 3, after applying the change Robert Kern and turning raw_input
to input, the code works in python 3:

lier...@compaq ~/junks $ python3 printhook.py
Python 3.1.2 (r312:79147, Apr 16 2010, 16:58:34)
[GCC 4.3.4]
linux2
Type "help", "copyright", "credits" or "license" for more info.
>>> print(32)
printhook(): 32

Note that assigning to __builtins__.print is different from assigning to
print. With the latter, you shadowed the print function in
__builtins__.print by putting your own print in the global namespace
(which in python really means module-level); while with the former
you're switching print in the interpreter level, the true global namespace.


### File test.py ###
from __future__ import print_function
import sys
from code import InteractiveInterpreter
from contextlib import contextmanager

def printhook(*args):
sys.stdout.write("printhook(): {0}\n".format(repr(args[0])))

@contextmanager
def global_printhook(printhook):
global print
print = printhook
yield
print = __builtins__.print

py = InteractiveInterpreter()

if not hasattr(sys, "ps1"): sys.ps1 = ">>> "
if not hasattr(sys, "ps2"): sys.ps2 = "... "

banner = ("Python %s\n%s\n" % (sys.version, sys.platform) +
  'Type "help", "copyright", "credits" or "license" '
  'for more info.\n')

sys.stdout.write(banner)
sys.stdout.write(sys.ps1)
while True:
try:
with global_printhook(printhook):
result = py.runsource(input())
if result is None:
sys.stdout.write(sys.ps2)
elif result is True:
py.runcode(result)
except EOFError:
break
else:
sys.stdout.write(sys.ps1)

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Globally override built-in print function?

2010-04-16 Thread Peter Otten
Dave W. wrote:

> I naively thought I could capture output from exec()'ed print
> invocations by (somehow) overriding 'print' globally.  But this
> seems not to be possible.  Or at least not easy:

Assigning a new function to the global print name affects only print() calls 
within your script, not the REPL. You have to redirect the latter and make 
sure that it is actually used instead of the print statement.

The easiest way I see to achieve that would be:

py.runsource("from __future__ import print_function")
py.runsource("from __main__ import printhook as print")

Peter

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Globally override built-in print function?

2010-04-15 Thread Dave W.
> > I naively thought I could capture output from exec()'ed print
> > invocations by (somehow) overriding 'print' globally.  But this
> > seems not to be possible.  

>
>old_print = __builtins__.print
>__builtins__.print = printhook
>yield
>__builtins__.print = old_print

I'm pretty sure this is semantically equivalent to my original code,
but I gave it a try anyway.  FWIW, it doesn't work, either. :-}

> But you really should replace sys.stdout and sys.stderr instead.

I'm starting to believe it, but... I thought that one of the
benefits of making print a function was that it *could* be globally
replaced. So far I've had no luck injecting a custom print
replacement into other modules.  Is this really not possible?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Globally override built-in print function?

2010-04-15 Thread Robert Kern

On 2010-04-15 18:08 PM, Dave W. wrote:

I naively thought I could capture output from exec()'ed print
invocations by (somehow) overriding 'print' globally.  But this
seems not to be possible.  Or at least not easy:

c:\d>test.py
Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit
(Intel)] win32
Type "help", "copyright", "credits" or "license" for more info.

print("Hello?")

Hello?




My custom print function isn't being called (see code below),
I guess because its only being overridden in the current module?
Is there some way to make InteractiveInterpreter/exec use my print
function, or is this simply not possible?

--

### File test.py ###
from __future__ import print_function
import sys
from code import InteractiveInterpreter
from contextlib import contextmanager

def printhook(*args):
 sys.stdout.write("printhook(): {0}\n".format(repr(args[0])))

@contextmanager
def global_printhook(printhook):
 global print
 print = printhook
 yield
 print = __builtins__.print


  old_print = __builtins__.print
  __builtins__.print = printhook
  yield
  __builtins__.print = old_print

But you really should replace sys.stdout and sys.stderr instead.

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

--
http://mail.python.org/mailman/listinfo/python-list


Globally override built-in print function?

2010-04-15 Thread Dave W.
I naively thought I could capture output from exec()'ed print
invocations by (somehow) overriding 'print' globally.  But this
seems not to be possible.  Or at least not easy:

c:\d>test.py
Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit
(Intel)] win32
Type "help", "copyright", "credits" or "license" for more info.
>>> print("Hello?")
Hello?
>>>

My custom print function isn't being called (see code below),
I guess because its only being overridden in the current module?
Is there some way to make InteractiveInterpreter/exec use my print
function, or is this simply not possible?

--

### File test.py ###
from __future__ import print_function
import sys
from code import InteractiveInterpreter
from contextlib import contextmanager

def printhook(*args):
sys.stdout.write("printhook(): {0}\n".format(repr(args[0])))

@contextmanager
def global_printhook(printhook):
global print
print = printhook
yield
print = __builtins__.print

py = InteractiveInterpreter()

if not hasattr(sys, "ps1"): sys.ps1 = ">>> "
if not hasattr(sys, "ps2"): sys.ps2 = "... "

banner = ("Python %s\n%s\n" % (sys.version, sys.platform) +
  'Type "help", "copyright", "credits" or "license" '
  'for more info.\n')

sys.stdout.write(banner)
sys.stdout.write(sys.ps1)
while True:
try:
with global_printhook(printhook):
result = py.runsource(raw_input())
if result is None:
sys.stdout.write(sys.ps2)
elif result is True:
py.runcode(result)
except EOFError:
break
else:
sys.stdout.write(sys.ps1)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: print function in python3.1

2009-11-23 Thread Terry Reedy

Dennis Lee Bieber wrote:
	Does Python 3.x include SQLite? 

 Of course ;-]

>>> import sqlite3
>>> dir(sqlite3)
['Binary', 'Cache', 'Connection', 'Cursor', 'DataError',
 [snip]
adapt', 'adapters', 'apilevel', 'complete_statement', 'connect', 
'converters', 'datetime', 'dbapi2', 'enable_callback_tracebacks', 
'enable_shared_cache', 'paramstyle', 'register_adapter', 
'register_converter', 'sqlite_version', 'sqlite_version_info', 
'threadsafety', 'time', 'version', 'version_info']


but is does not seem to have exposed escape_string function

--
http://mail.python.org/mailman/listinfo/python-list


Re: print function in python3.1

2009-11-23 Thread Diez B. Roggisch
Anjanesh Lekshminarayanan wrote:

>> Maybe it would help if you explained what you are actually trying to
>> accomplish.
> 
> import csv
> f = csv.reader(open('data.txt'), delimiter='\t') # 2GB text file
> sql = "INSERT INTO `data` VALUES (NULL,%s,%s,%s,%s,%s);"
> for row in f:
> print (sql, (row[0],row[1],row[2],row[3],row[4]))
> 
> $ python3 parse.py3 > data.sql
> 
> But because of print() being a function in Py3,
> print (sql, (row[0],row[1],row[2],row[3],row[4]))
> prints
> INSERT INTO `data` VALUES (NULL, '%s', '%s', '%s', '%s', '%s');
> ('142', 'abcde', '2006-03-01 05:17:14', '', '')
> instead of
> INSERT INTO `data` VALUES (NULL, '142', 'abcde', '2006-03-01 05:17:14',
> '', '');

No. It does so because you don't use 

  print(sql % (row[0],row[1],row[2],row[3],row[4]))

And that has nothing to do with print being a function or not.

Diez


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: print function in python3.1

2009-11-23 Thread Anjanesh Lekshminarayanan
> Maybe it would help if you explained what you are actually trying to
> accomplish.

import csv
f = csv.reader(open('data.txt'), delimiter='\t') # 2GB text file
sql = "INSERT INTO `data` VALUES (NULL,%s,%s,%s,%s,%s);"
for row in f:
print (sql, (row[0],row[1],row[2],row[3],row[4]))

$ python3 parse.py3 > data.sql

But because of print() being a function in Py3,
print (sql, (row[0],row[1],row[2],row[3],row[4]))
prints
INSERT INTO `data` VALUES (NULL, '%s', '%s', '%s', '%s', '%s');
('142', 'abcde', '2006-03-01 05:17:14', '', '')
instead of
INSERT INTO `data` VALUES (NULL, '142', 'abcde', '2006-03-01 05:17:14', '', '');

Anjanesh
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: print function in python3.1

2009-11-23 Thread Carsten Haese
Anjanesh Lekshminarayanan wrote:
> As of now, there is no mysql adaptor for Python3. Hence cant use 
> escape_string()

Maybe it would help if you explained what you are actually trying to
accomplish.

--
Carsten Haese
http://informixdb.sourceforge.net

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: print function in python3.1

2009-11-23 Thread Anjanesh Lekshminarayanan
As of now, there is no mysql adaptor for Python3. Hence cant use escape_string()

> I don't have the slightest clue what you want to say with that.

-- 
Anjanesh Lekshmnarayanan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: print function in python3.1

2009-11-23 Thread Diez B. Roggisch
Anjanesh Lekshminarayanan wrote:

>> Depending on your DB-adapter, you are out of luck here. Either connect to
>> a db even if you don't need it, or try & see if you can locate the
>> implementation in the module somehow.
> 
> ImportError: No module named MySQLdb
> MySQLdb only available in Python2.
> 

I don't have the slightest clue what you want to say with that.

Diez
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: print function in python3.1

2009-11-23 Thread Anjanesh Lekshminarayanan
> Depending on your DB-adapter, you are out of luck here. Either connect to a 
> db even if you don't need it, or try & see if you can locate the 
> implementation in the module somehow.

ImportError: No module named MySQLdb
MySQLdb only available in Python2.

-- 
Anjanesh Lekshmnarayanan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: print function in python3.1

2009-11-23 Thread Diez B. Roggisch
Anjanesh Lekshminarayanan wrote:

> Python 3.1.1
> 
> sql = "INSERT INTO `tbl` VALUES (NULL, '%s', '%s', '%s', '%s', '%s');"
> for row in fp:
> print (sql, (row[0],row[1],row[2],row[3],row[4]))
> .
> INSERT INTO `tbl` VALUES (NULL, '%s', '%s', '%s', '%s', '%s'); ('142',
> 'abc', '2006-04-09 02:19:24', '', '')
> .
> Why is it showing %s in the output ?

Because you gave it to it. How should it know that you want the %s to be
replaced with the other parameters? That's what the %-operator is for.

> 
> 1. I dont want to sql % () because that doesnt escape the strings
> 2. I cant use conn.escape_string(r) because Im not connected to a
> database. Output script to file and import to database loated
> elsewhere.

Depending on your DB-adapter, you are out of luck here. Either connect to a
db even if you don't need it, or try & see if you can locate the
implementation in the module somehow.

E.g. MySQLdb has the function exposed as "escape_string", not only on a
connection.

Diez

-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >