Re: Don't rebind built-in names* - it confuses readers

2013-06-11 Thread Terry Jan Reedy

On 6/10/2013 10:56 PM, Steven D'Aprano wrote:


I was initially confused
and reading the code still takes a small bit of extra mental energy.
Idle stays confused and will wrongly color the list instance name until
it is changed. Calling the file list 'fnames' or 'filenames' would have
been clearer to both me and Idle.


Correct. The downside of editors that colourise text is that sometimes
they colourise it wrong. In this case, how is the editor supposed to know
that list no longer refers to the built-in list?

This is yet another good argument for being cautious about shadowing
built-ins.


After posting I remembered that there are also colorized text blocks on 
web pages. Each person will have to decide for themselves whether the 
convenience of reusing a builtin name is worth having their code 
mis-colorized. As a reader, I decided that it is not.


tjr



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


Re: Newbie: question regarding references and class relationships

2013-06-10 Thread Terry Jan Reedy

On 6/10/2013 12:09 PM, Rui Maciel wrote:


We've established that you don't like attribute declarations, at least those
you describe as not fulfill a technical purpose.  What I don't understand is
why you claim that that would cause nothing but trouble.


Three answers:
Look how much trouble it has already caused ;-)
Since you are a self-declared newbie, believe us!
Since, be definition, useless code can do no good, it can only cause 
trouble. Think about it.


Terry


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


Re: Newbie: question regarding references and class relationships

2013-06-10 Thread Terry Jan Reedy

On 6/10/2013 9:18 AM, Rui Maciel wrote:


class Model:
 points = []
 lines = []


Unless you actually need keep the points and lines ordered by entry 
order, or expect to keep sorting them by whatever, sets may be better 
than lists. Testing that a point or line is in the model will be faster, 
as will deleting one by its identify.



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


Re: py_compile vs. built-in compile, with __future__

2013-06-10 Thread Terry Jan Reedy

On 6/10/2013 11:33 AM, dhyams wrote:

The built-in compile() function has a flags parameter that one can
use to influence the __future__ mechanism. However,
py_compile.compile, which I'm using to byte-compile code, doesn't
have an equivalent means to do this.


That flag was added to compile bacause it is needed to compile 
expressions and single statements, whether in string or ast form, that 
use future syntax. It is impossible to include a future statement with 
either. It is not needed for compiling multiple statements.



Is this by design, or would this be considered a bug?


Design, not needed.


import __future__
py_compile.compile(foobar.py,flags=__future__.CO_FUTURE_DIVISION)


Put the future statement inside foobar.py just as you would do if 
running it from the command line. Notice that there is no command-line 
future flag either.


Terry



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


Re: Newbie: question regarding references and class relationships

2013-06-10 Thread Terry Jan Reedy

On 6/10/2013 4:13 PM, Rui Maciel wrote:

Terry Jan Reedy wrote:


Three answers:
Look how much trouble it has already caused ;-)
Since you are a self-declared newbie, believe us!
Since, be definition, useless code can do no good, it can only cause
trouble. Think about it.


I don't doubt that there might good reasons for that, but it is always
preferable to get the rationale behind a decision to be able to understand
how things work and how to do things properly.


I agree actually. But sometimes is it hard to articulate 'good reasons' 
for a principle based on the integration of over a decade of experience. 
I was really trying to point to the difference between


'I will not accept the experience-based advice until enough good reasons 
are presented.' and


'I will provisionally accept the advice but I would still like to know why.'

Another principle similar to 'Don't add extraneous code' is 'Don't 
rebind builtins*'. I have a separate post for that.


Terry



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


Don't rebind built-in names* - it confuses readers

2013-06-10 Thread Terry Jan Reedy

Many long-time posters have advised Don't rebind built-in names*.

* Unless you really mean to mask it, or more likely wrap it, such as 
wrapping print to modify some aspect of its operation than one cannot do 
with its keyword parameters. The point for this post is that such 
wrapping modify or extend the basic meaning of the builtin, but do not 
abolish it.


Reasons have been given in various related forms: 'my long experience 
tells me its bad', 'you may need the builtin later', 'you may forget 
that you rebound the builtin, 'it can lead to subtle bugs, etc.


Leaving aside the code writer and code operation, I recently discovered 
that it is not nice for readers, whether humans or programs.


For instance, open Lib/idlelib/GrepDialog.py in an editor that colorizes 
Python syntax, such as Idle's editor, jump down to the bottom and read 
up, and (until it is patched) find

list.append(fn)
with 'list' colored as a builtin. Stop. That looks wrong. List.append 
needs two arguments: a list instance and an object to append to the 
list. The 'solution' is in a previous line

list = []
Reading further, one sees that the function works with two lists, a list 
of file names, unfortunately called 'list', and a list of 
subdirectories, more sensibly call 'subdirs'. I was initially confused 
and reading the code still takes a small bit of extra mental energy. 
Idle stays confused and will wrongly color the list instance name until 
it is changed. Calling the file list 'fnames' or 'filenames' would have 
been clearer to both me and Idle.


--
Terry Jan Reedy

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


Re: Idiomatic Python for incrementing pairs

2013-06-08 Thread Terry Jan Reedy

On 6/8/2013 12:16 AM, Tim Chase wrote:

On 2013-06-08 07:04, Carlos Nepomuceno wrote:

alpha, beta = (1 if some_calculation(params) else 0, 1 if
other_calculation(params) else 0)


This one sets them to absolute values, rather than the incrementing
functionality in question:


   alpha += temp_a
   beta += temp_b


The actual code in question does the initialization outside a loop:

   alphas_updated = betas_updated = 0
   for thing in bunch_of_things:
 a, b = process(thing)
 alphas_updated += a
 betas_updated += b


I am pretty sure that this is the faster way to get the result.


and it just bugs me as being a little warty for having temp
variables when Python does things like tuple-unpacking so elegantly.


So use it ;-).


That said, as mentioned in a contemporaneous reply to Jason, I haven't
found anything better that is still readable.


The generalization of what you want is a mutable vector with an in-place 
augmented assignment version of element by element addition. That 
probably has been written. Nnmpy arrays do vector addition and maybe do 
it in-place also (I just do ot know). But here is a custom class for the 
problem you presented.


def process(val):
return val, 2*val

class Pair(list):
def __init__(self, a, b):
self.append(a)
self.append(b)
def inc(self, a, b):
self[0] += a
self[1] += b

pair = Pair(0, 0)
for val in [1,2,3]:
pair.inc(*process(val))

print(pair)

[6, 12]

This is cleaner but a bit slower than your in-lined version. I did not 
use __iadd__ and += because unpacking 'other' (here the process return) 
in the call does the error checking ('exactly two values') for 'free'.


--
Terry Jan Reedy



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


Re: Mistakes in documentation

2013-06-06 Thread Terry Jan Reedy

On 6/6/2013 8:01 AM, Paul Volkov wrote:

Where can I submit little mistakes in Python documantation?
I found one while browsing tutorial.pdf (Python 3.3.2):

Section 3.1 says (on page 12):
  word[2:5] # characters from position 2 (included) to 4 (excluded)
’tho’

Shouldn't the comment say 5 (excluded) or 4 (included) instead?


At the bottom of the index page, in the Meta information section,
is an entry for the Reporting bugs doc. It says to email d...@python.org
or to use the tracker for a persistent record. This is followed by an
explanation of using the tracker.

Terry




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


Re: Bools and explicitness [was Re: PyWart: The problem with print]

2013-06-05 Thread Terry Jan Reedy

On 6/5/2013 2:11 AM, Russ P. wrote:


But then, what would you expect of a language that allows you to
write

x = 1

 x = Hello


It's all loosey goosey -- which is fine for many applications but
certainly not for critical ones.


I believe Shedskin, a Python *subset* compiler*, will reject that, 
because it compiles ints to C ints. Some code checkers might too.



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


Dijkstra (was Re: Source code to identify user through browser?)

2013-06-05 Thread Terry Jan Reedy

On 6/5/2013 6:07 PM, Carlos Nepomuceno wrote:


Didn't know he was such a humorist! lol

Although I prefer when he's serious:

http://www.cs.utexas.edu/~EWD/transcriptions/EWD10xx/EWD1094.html


pythonic summary:
Let S be an finite iterable of numbers (make it not an iterable if one 
interprets the conclusion as requiring reiteration) and let n = len(S) 
(or len(list(S)) if need be). The if n  2 and len(set(S))  1,

n * min(S)  sum(S)  max(S)  # easily shown by induction on n

If the n = 1 or the items in S are all the same,
n*min == sum == n*max

I might call this the 'Averages are not extreme' theorem.

Corollary: if min(s) == 1 and sum(S)  n, then max(S)  1
'Pigeonhole Principle'

--
Terry Jan Reedy



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


Re: Interactive interpreter hooks

2013-06-03 Thread Terry Jan Reedy

On 6/3/2013 3:55 AM, Steven D'Aprano wrote:

The sys module defines two hooks that are used in the interactive
interpreter:

* sys.displayhook(value) gets called with the result of evaluating the
line when you press ENTER;

* sys.excepthook(type, value, traceback) gets called with the details of
the exception when your line raises an exception.

Is there a way to hook into the interactive interpreter *before* it is
evaluated? That is, if I type len([]) at the prompt and hit ENTER, I
want a hook that runs before len([]) is evaluated to 0, so that I get the
string len([]).


You have not said what you are actually trying to do, but you could 
definitely modify Idle to do something with user input before it sends 
it to the user process.





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


Re: Python 2-3 compatibility

2013-06-02 Thread Terry Jan Reedy

On 6/2/2013 10:13 AM, Jason Swails wrote:


Because Python 2.4 and 2.5 don't support the

except Exception as err:

syntax, I've used

except Exception, err:

Is there any way of getting this effect in a way compatible with Py2.4
and 3.x?


Don't do either. Just catch the exception with 'except Exception:' and 
access the details in the body. I googled 'python 2 to 3 exceptions' and 
the second hit is http://python3porting.com/noconv.html which covers 
what you are doing ;-). From that page


If you need to support Python versions lower than Python 2.6 and you 
need access to the exception that was raised, you can get that in all 
versions through the exc_info() function:


 import sys
 try:
... a = 1/'0'
... except (ZeroDivisionError, TypeError):
... e = sys.exc_info()[1]
... print(e.args[0])
unsupported operand type(s) for /: 'int' and 'str'

There are more tips on that page, a reference to the six module, and 
more hits on the search page. Good luck. You are not the first to 
support the same range of versions (and for the same reasons).


--
Terry Jan Reedy




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


Re: Future standard GUI library

2013-06-01 Thread Terry Jan Reedy

On 6/1/2013 4:46 PM, Chris Angelico wrote:

On Sun, Jun 2, 2013 at 4:18 AM, Wolfgang Keller felip...@gmx.net wrote:



And by screenworkers I didn't refer to programmers. Those people
rarely have to use the stuff that they implement.


Of course not, programmers never use software they've themselves
written. Never. Not in a million... oh wait, what's this I have? Hmm,
gcc used to compile gcc, RosMud being used by Rosuav, Neil Hodgson
using SciTE... naw, they're all statistical anomalies, carry on!


And I use Idle to improve Idle.

I use the HgWorkbench front-end to hg because point and click is often 
*faster* for me than remember (or look up command and arg) and type 
(without error, or correction after error).


Now back to ignoring the troll.

Terry


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


Re: The state of pySerial

2013-05-29 Thread Terry Jan Reedy

On 5/29/2013 4:00 PM, William Ray Wing wrote:

On May 29, 2013, at 2:23 PM, Ma Xiaojun damage3...@gmail.com wrote:


Hi, all.

pySerial is probably the solution for serial port programming.
Physical serial port is dead on PC but USB-to-Serial give it a second
life. Serial port stuff won't interest end users at all. But it is
still used in the EE world and so on. Arduino uses it to upload
programs. Sensors may use serial port to communicate with PC. GSM
Modem also uses serial port to communicate with PC.

Unforunately, pySerial project doesn't seem to have a good state. I
find pySerial + Python 3.3 broken on my machine (Python 2.7 is OK) .
There are unanswered outstanding bugs, PyPI page has 2.6 while SF
homepage still gives 2.5.

Any idea?
--
http://mail.python.org/mailman/listinfo/python-list


Let me add another vote/request for pySerial support.  I've been using it with 
python 2.7 on OS-X, unaware that there wasn't a path forward to python 3.x.  If 
an external sensor absolutely positively has to be readable, then RS-232 is the 
only way to go.  USB interfaces can and do lock up if recovery from a power 
failure puts power on the external side before the computer has finished 
initializing the CPU side.  RS-232, bless its primitive heart, could care less.


Then 'someone' should ask the author his intentions and offer to help or 
take over.


I did some RS-232 interfacing in the  1980s, and once past the fiddly 
start/stop/parity bit, baud rate, and wiring issues, I had a program run 
connected to multiple machines for years with no more interface problems.


Terry


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


Re: The state of pySerial

2013-05-29 Thread Terry Jan Reedy

On 5/29/2013 3:47 PM, Grant Edwards wrote:

On 2013-05-29, Ma Xiaojun damage3...@gmail.com wrote:


pySerial is probably the solution for serial port programming.
Physical serial port is dead on PC but USB-to-Serial give it a second
life. Serial port stuff won't interest end users at all. But it is
still used in the EE world and so on. Arduino uses it to upload
programs. Sensors may use serial port to communicate with PC. GSM
Modem also uses serial port to communicate with PC.

Unforunately, pySerial project doesn't seem to have a good state. I
find pySerial + Python 3.3 broken on my machine (Python 2.7 is OK) .
There are unanswered outstanding bugs, PyPI page has 2.6 while SF
homepage still gives 2.5.

Any idea?


Volunteer as a maintainer and start fixing bugs?


It seems to be getting around 200 downloands a day. Quite worth someone 
supporting it.



I use pyserial regularly, and the current version works fine for me,
but I'm using Python 2.7. There are still too many libraries that
don't support 3.x for me to consider using 3.x for real work.


The only download is a .exe. It it just the executable binary or is that 
a zip unpacker with source?




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


Re: Python #ifdef

2013-05-28 Thread Terry Jan Reedy

On 5/28/2013 6:25 PM, Joel Goldstick wrote:

On Tue, May 28, 2013 at 6:18 PM, Mark Lawrence breamore...@yahoo.co.uk
mailto:breamore...@yahoo.co.uk wrote:



On 28/05/2013 20:46, Carlos Nepomuceno wrote:
I'd like to have something like '#ifdef' to mix code from Python
2 and 3 in a single file.



https://pypi.python.org/pypi/__six/1.3.0
https://pypi.python.org/pypi/six/1.3.0



my original response was from cell phone.  I just answered that you
can't do ifdefs, implying that there is no preprocessor in python.  I
learned a lot of things I didn't know reading the thread, but I wonder
if it is a good idea in general to try to write code like this.  --
combined 2.x/3.x codebase can be a bear to maintain.


Many people have come to prefer a) a single 23 codebase over b) 
separate 2 and 3 codebases or c) a single 2 codebase repeatedly 
converted to a 3 codebase with 2to3.


They use 2to3 once (well, a few times) to discover differences that need 
to be considered.


For 2.7 and 3.x, the future imports are enough for some code. The six 
module handles harder cases.



I wouldn't do it
unless there was some imposing reason that I must.  Its not just print()
-- that isn't bad, but changes in module names (urllib),


I believe six handles that

 arithmetic, and

from __future__ import integer_division  # spelling?
handles the only change


unicode


Use unicode consistently and
from __future__ import unicode_literals  # spelling?
or the re-addition u'' prefix do quite well.

Otherwise, do not use things that evaporated, like apply() and classic 
classes. (Inherit from object if nothing else.)


This is all hearsay coming from me ;-).

Terry


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


Re: Python error codes and messages location

2013-05-27 Thread Terry Jan Reedy

On 5/27/2013 12:54 PM, Carlos Nepomuceno wrote:


I think PEP 3151 is a step ahead! That's almost exactly what I was looking for. 
Why did it take so long to have that implemented?   



Since this PEP involved changing existing features, rather than adding 
something mew, it probably took moe time and discussion to get consensus 
on details of the change.


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


Re: Short-circuit Logic

2013-05-26 Thread Terry Jan Reedy

On 5/26/2013 7:11 AM, Ahmed Abdulshafy wrote:


  if not allow_zero and abs(x)  sys.float_info.epsilon:
 print(zero is not allowed)


The reason for the order is to do the easy calculation first and the 
harder one only if the first passes.




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


Re: Output from to_bytes

2013-05-26 Thread Terry Jan Reedy

On 5/26/2013 8:02 AM, Mok-Kong Shen wrote:

for k in range(8,12,1):
  print(k.to_bytes(2,byteorder='big'))


http://bugs.python.org/issue9951
http://bugs.python.org/issue3532

import binascii as ba
for k in range(8,12,1):
print(ba.hexlify(k.to_bytes(2,byteorder='big')))

b'0008'
b'0009'
b'000a'
b'000b'


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


Re: Encodign issue in Python 3.3.1 (once again)

2013-05-26 Thread Terry Jan Reedy

On 5/26/2013 12:36 PM, Νίκος Γκρ33κ wrote:

This is the code that although correct becaus it works with englisg(standARD 
ASCII letters) it wont with Greek:

if( log ):
name = log
# print specific client header info
cur.execute('''SELECT hits, money FROM clients WHERE name = %s''', 
(name,) )
data = cur.fetchone()
===

The following is the live output of: tail -F /usr/local/apache/logs/error_log 


[Sun May 26 19:24:04 2013] [error] [client 46.12.46.11] Error in 
sys.excepthook:, referer: http://superhost.gr/cgi-bin/pelatologio.py
[Sun May 26 19:24:04 2013] [error] [client 46.12.46.11] UnicodeEncodeError: 
'ascii' codec can't encode characters in position 2050-2056: ordinal not in 
range(128), referer: http://superhost.gr/cgi-bin/pelatologio.py
[Sun May 26 19:24:04 2013] [error] [client 46.12.46.11] , referer: 
http://superhost.gr/cgi-bin/pelatologio.py
[Sun May 26 19:24:04 2013] [error] [client 46.12.46.11] Original exception 
was:, referer: http://superhost.gr/cgi-bin/pelatologio.py
[Sun May 26 19:24:04 2013] [error] [client 46.12.46.11] Traceback (most recent 
call last):, referer: http://superhost.gr/cgi-bin/pelatologio.py
[Sun May 26 19:24:04 2013] [error] [client 46.12.46.11]   File pelatologio.py, line 
122, in module, referer: http://superhost.gr/cgi-bin/pelatologio.py
[Sun May 26 19:24:04 2013] [error] [client 46.12.46.11] 
cur.execute('''SELECT hits, money FROM clients WHERE name = %s''', (name,) ), 
referer: http://superhost.gr/cgi-bin/pelatologio.py



[Sun May 26 19:24:04 2013] [error] [client 46.12.46.11]   File 
/opt/python3/lib/python3.3/site-packages/pymysql/cursors.py, line 108, in 
execute, referer: http://superhost.gr/cgi-bin/pelatologio.py
[Sun May 26 19:24:04 2013] [error] [client 46.12.46.11] query = 
query.encode(charset), referer: http://superhost.gr/cgi-bin/pelatologio.py
[Sun May 26 19:24:04 2013] [error] [client 46.12.46.11] UnicodeEncodeError: 
'latin-1' codec can't encode characters in position 46-52: ordinal not in 
range(256), referer: http://superhost.gr/cgi-bin/pelatologio.py


This appears to be an issue with your mysql database and how you set it 
up.. It is using charset='latin-1' whereas you need it to consistently 
use charset='utf8' both for storing strings and for retrieval. Check the 
mysql manual or ask on a mysql list for how to do that. I have no idea 
so don't ask me, or send mail to my emall address.



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


Re: Cutting a deck of cards

2013-05-26 Thread Terry Jan Reedy

On 5/26/2013 3:54 PM, Carlos Nepomuceno wrote:



From: usenetm...@solar-empire.de

[...]

Not in Python3.x

decks = 6
list(range(13 * 4 * decks)) == range(13 * 4 * decks)

False

Adiaŭ
Marc



What does list(range(13 * 4 * decks)) returns in Python 3?  


A list, obviously. What you should ask is what range returns in Python 
3, and you should install python 3 and try it, and list its attributes.




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


Re: Short-circuit Logic

2013-05-26 Thread Terry Jan Reedy

On 5/26/2013 4:22 PM, Roy Smith wrote:

In article mailman.2196.1369599562.3114.python-l...@python.org,
  Terry Jan Reedy tjre...@udel.edu wrote:


On 5/26/2013 7:11 AM, Ahmed Abdulshafy wrote:


   if not allow_zero and abs(x)  sys.float_info.epsilon:
  print(zero is not allowed)


The reason for the order is to do the easy calculation first and the
harder one only if the first passes.


This is a particularly egregious case of premature optimization.  You're
worried about how long it takes to execute abs(x)?  That's silly.


This is a particularly egregious case of premature response. You're 
ignoring an extra name lookup and two extra attribute lookups. That's silly.


That's beside the fact that one *must* choose, so any difference is a 
reason to act rather than being frozen like Buridan's ass.

http://en.wikipedia.org/wiki/Buridan%27s_ass

If you wish, replace 'The reason' with 'A reason'. I also the logical 
flow as better with the order given.






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


Re: Simple algorithm question - how to reorder a sequence economically

2013-05-24 Thread Terry Jan Reedy

On 5/24/2013 4:14 AM, Peter Brooks wrote:

What is the easiest way to reorder a sequence pseudo-randomly?

That is, for a sequence 1,2,3,4 to produce an arbitrary ordering (eg
2,1,4,3) that is different each time.

I'm writing a simulation and would like to visit all the nodes in a
different order at each iteration of the simulation to remove the risk
of a fixed order introducing spurious evidence of correlation.


random module has a shuffle function I believe


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


Re: Newbie question about evaluating raw_input() responses

2013-05-23 Thread Terry Jan Reedy

On 5/23/2013 12:47 AM, Steven D'Aprano wrote:

On Wed, 22 May 2013 22:31:04 +, Alister wrote:


Please write out 1000 time (without using any form of loop)

NEVER use input in python 3.0 it is EVIL*



But all joking aside, eval is dangerous, yes, but it is not evil.


He put that label on *input*, not eval -- I presume for hiding dangerous 
eval.



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


Re: subclassing from unittest

2013-05-23 Thread Terry Jan Reedy

On 5/23/2013 2:58 AM, Ulrich Eckhardt wrote:


Well, per PEP 8, classes use CamelCaps, so your naming might break
automatic test discovery. Then, there might be another thing that could
cause this, and that is that if you have an intermediate class derived
from unittest.TestCase, that class on its own will be considered as test
case! If this is not what you want but you still want common
functionality in a baseclass, create a mixin and then derive from both
the mixin and unittest.TestCase for the actual test cases.


This is now standard practice, gradually being implemented everywhere in 
the CPython test suite, for testing C and Py versions of a module.


class TestXyz():
  mod = None
  test_a, etc, methods

class TestXyz_C(TestXyz, TextCase):  # Test C version
  mod = support.import_fresh_module('_xyz')  # approximately right

class TestXyz_Py(TestXyz, TextCase):  # Test Python version
  mod = support.import_fresh('xyz')

This minimizes duplication and ensures that both implementations get 
exactly the same tests.


tjr


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


Re: how to get the socket module compiled with SSL support

2013-05-23 Thread Terry Jan Reedy

On 5/23/2013 9:58 AM, Kihup Boo wrote:

I am trying to make an HTTPS connection and read that HTTPS support is
only available if the socket module was compiled with SSL support.

_http://www.jython.org/docs/library/httplib.html_

Can someone elaborate on this? Where can I get the socket module for
HTTPS, or how do I build one if I have to?


This is mostly a CPython oriented list. Any prebuilt CPython binary you 
get likely has SSL support compiled in. If you want to know about the 
jython socket module, you should check on a jython list, or just try it.



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


Re: PEP 378: Format Specifier for Thousands Separator

2013-05-23 Thread Terry Jan Reedy

On 5/23/2013 2:42 PM, Dave Angel wrote:

On 05/23/2013 11:26 AM, Carlos Nepomuceno wrote:





eggs(a,f)

Traceback (most recent call last):
File pyshell#29, line 1, in module
eggs(a,f)
File pyshell#1, line 1, in eggs
def eggs(spam, ham): return spam % ham
TypeError: not all arguments converted during string formatting

'%s'%(5%3)

'2'


So % doesn't handle tuples! Why's that? Is it intentional (by design)?



It's a conflict in the design.  A tuple is used to supply multiple
arguments to the % operator.  So if you want to have a tuple as the
first argument, you need to enclose it in another tuple.


The problem is that interpolating 1 to many items into a string is *not* 
a binary operation. The needed hack to pretend that it is, using a tuple 
to represent multiple items rather than just itself, was one of the 
reasons for making string formatting a honest function, where multiple 
items to be formatted are passed as multiple arguments.



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


Re: Non-identifiers in dictionary keys for **expression syntax

2013-05-23 Thread Terry Jan Reedy

On 5/23/2013 2:52 PM, Matthew Gilson wrote:

This is a question regarding the documentation around dictionary
unpacking.  The documentation for the call syntax
(http://docs.python.org/3/reference/expressions.html#grammar-token-call)
says:

If the syntax **expression appears in the function call, expression
must evaluate to a mapping, the contents of which are treated as
additional keyword arguments.

That's fine, but what is a keyword argument?  According to the glossary
(http://docs.python.org/3.3/glossary.html):

/keyword argument/: an argument preceded by an identifier (e.g. name=)
in a function call or passed as a value in a dictionary preceded by **.


It appears that the requirement has been relaxed (in the previous 
quote), so that 'dictionary' should also be changed to 'mapping'. It 
might not hurt to add 'The key for the value should be an identifier.'


As far as I'm concerned, this leads to some ambiguity in whether the
keys of the mapping need to be valid identifiers or not.


I think you are being too lawyerly. The pretty clear and sensible 
implication is that the key for the value should be a string with a 
valid identifier. If it is anything else, you are on your own and 
deserve any joy or pain that results ;=)



Using Cpython, we can do the following:

  def func(**kwargs):
   print kwargs

  d = {'foo bar baz':3}

So that might lead us to believe that the keys of the mapping do not
need to be valid identifiers.


There are two ways to pass args to func to be gathered into kwargs; 
explicit key=val pairs and **mapping, or both.

func(a=1, b='hi', **{'foo bar baz':3})
#
{'foo bar baz': 3, 'a': 1, 'b': 'hi'}

So func should not expect anything other than identifier strings.

  However, the previous function does not

work with the following dictionary:

 d = {1:3}

because not all the keys are strings.


So CPython checks that keys are strings, because that is cheap, but not 
that the strings are identifiers, because that would be more expensive. 
Just because an implementation allow somethings (omits a check) for 
efficiency does not mean you should do it.


globals()[1] = 1
works, but is not normally very sensible or useful.


 Is there a way to petition to get this more rigorously defined?


bugs.python.org
The problem is that mandating a rigorous check by implementations makes 
Python slower to the detriment of sensible programmers.





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


Re: Myth Busters: % this old style of formatting will eventually be removed from the language

2013-05-22 Thread Terry Jan Reedy

On 5/22/2013 10:24 AM, Denis McMahon wrote:


Indeed, removing %-formatting could break a substantial amount of live
code, with potentially significant maintenance effort in the user


While I would like to see % formatting go away everntually*, other 
developers would not. In any case, I agree that it should not disappear 
until there is a foolproof conversion tool, probably custom written. I 
am working on other things.


* perhaps in 10 years?, when all 2.x code that is going to be converted 
has been converted


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


Re: What was the project that made you feel skilled in Python?

2013-05-22 Thread Terry Jan Reedy

On 5/22/2013 9:05 AM, Ben Finney wrote:


I wanted to simulate a particular board game, and had others in mind
with some common mechanics.

This resulted in a library for rolling dice in different combinations,
and looking up result tables URL:https://pypi.python.org/pypi/alea.


Have you cosidered adding a description so it can be found be a search?
A 3.3 version?

Simulate game randomizers and lookup: dice rolls, card drawing, 
spinners, ...



Eventually I wanted to extend it to know about custom decks of cards,
and the different ways those are handled in board games.

The unifying theme was a library of routines for simulating the random
elements (dice, cards, tables, spinners, etc.) in any board game.

A little over-engineered, I'll freely admit. But it did give me a sense
of being at home in Python and knowing that this is a good language for
getting things done the right way.




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


Re: subclassing from unittest

2013-05-22 Thread Terry Jan Reedy

On 5/22/2013 11:32 AM, Charles Smith wrote:

Have you red this? I will suggest some specifics.
http://www.catb.org/esr/faqs/smart-questions.html


I'd like to subclass from unittest.TestCase.


What version of Python.

 I observed something interesting and wonder if anyone can explain 
what's going on... some

subclasses create  null tests.

I can create this subclass and the test works:


What does 'works' mean?


   class StdTestCase (unittest.TestCase):
   blahblah


I bet that this (and the rest of your 'code' is not what you actually 
ran. Unless blahblah is bound (to what?), this fails with NameError.

Give us what you ran so we can run it too, and modify it.


and I can create this subsubclass and the test works:

   class aaaTestCase (StdTestCase):
   moreblahblah

but if I create this subsubclass (or any where the first letter is
capital):

   class AaaTestCase (StdTestCase):
   differentblahblah

the test completes immediately without any work being done.


What does this mean? I see no difference with the following

import unittest
class StdTestCase (unittest.TestCase): pass
class lowerSub(StdTestCase): pass
class UpperSub(StdTestCase): pass

unittest.main(verbosity=2, exit=False)

# prints (3.3)
--
Ran 0 tests in 0.000s

OK

Same as before the subclasses were added.

--
Terry Jan Reedy


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


Re: Future standard GUI library

2013-05-20 Thread Terry Jan Reedy

On 5/20/2013 1:04 AM, Vito De Tullio wrote:

Terry Jan Reedy wrote:


Do you think tkinter is going to be the standard python built-in gui
solution as long as python exists?


AT the moment, there is nothing really comparable that is a realistic
candidate to replace tkinter.


FLTK? (http://www.fltk.org/index.php)


tkinter is the Python wrapper of the tk library, just as wxpython is the 
python wrapper of the wx library. I do not see a py-fltk wrapper.



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


Re: What was the project that made you feel skilled in Python?

2013-05-20 Thread Terry Jan Reedy

On 5/20/2013 3:36 PM, Thomas Murphy wrote:


talking about patches in the stdlib? Is there a separate library of
patches?


http://bugs.python.org
http://docs.python.org/devguide/



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


Re: Harmonic distortion of a input signal

2013-05-19 Thread Terry Jan Reedy

On 5/19/2013 6:49 PM, Oscar Benjamin wrote:


import numpy as np


Create a square wave signal:


x = np.zeros(50)
x[:25] = -1
x[25:] = +1
x

array([-1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1.,
-1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1.,  1.,
 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,
 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.])

Compute the magnitude spectrum:


spect = abs(np.fft.fft(x)[:25])
spect

array([  0.,  31.85194222,   0.,  10.67342282,
  0.,   6.47213595,   0.,   4.69726931,
  0.,   3.73254943,   0.,   3.13762901,
  0.,   2.7436023 ,   0.,   2.47213595,
  0.,   2.28230601,   0.,   2.15105461,
  0.,   2.06487174,   0.,   2.01589594,   0.])

Find the index of the maximum element:


np.argmax(spect)

1

So the peak is the lowest non-zero frequency component of the DFT. In
Hz this corresponds to a frequency of 1/T where T is the duration of
the signal.


While you were answering a specific question, I think the above is a 
nice tutorial example, because it is more meaningful than arbitrary 
operations applied to random data.




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


Re: python script is not running

2013-05-18 Thread Terry Jan Reedy

On 5/18/2013 6:12 AM, Avnesh Shakya wrote:

hi,
 i want to run python script which generating data into json fromat, I am 
using crontab, but it's not executing...
my python code--
try.py --

import json
import simplejson as json
import sys

def tryJson():
 saved = sys.stdout
 correctFile = file('data.json', 'a+')
 sys.stdout = correctFile


Don't need to change stdout.


 result = []
 i = 1
 for i in range(5):
 info = {
 'a': i+1,
 'b': i+2,
 'c': i+3,
}
 result.append(info)


What is you want to add print result for debugging?


 if result:
 print json.dumps(result, indent=6)


Either use print  correctFile, correctFile.write (do you really want 
the extra '\n' that print adds?), or, do the future import of print as 
function and pass correctFile as the file argument



 sys.stdout = saved
 correctFile.close()
tryJson()



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


Re: how to run another file inside current file?

2013-05-18 Thread Terry Jan Reedy

On 5/18/2013 7:15 AM, Kevin Xi wrote:

Hi,
It's better to specify version of python you work with.


Absolutely.


 I know nothing

about python 3 but in python 2 you can do this with `exec`. Example:

  f = file('otherFile.py')
  exec f


Py 2 has execfile that does the above. Py 3 do as above except that exec 
is a function.


with open('otherfile.py') as f:
  exex(f)



For more, read the doc:
http://docs.python.org/2.7/reference/simple_stmts.html#the-exec-statement
HTH





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


Re: Future standard GUI library

2013-05-18 Thread Terry Jan Reedy

On 5/18/2013 10:03 AM, Beinan Li wrote:

Not sure if this is the right place to talk about this.


It is.


Even less sure if I can
move this discussion to tkinter list,


The idea of replacing tkinter is not about improving tkinter ;-).


Do you think tkinter is going to be the standard python built-in gui
solution as long as python exists?


AT the moment, there is nothing really comparable that is a realistic 
candidate to replace tkinter. Tkinter is a tcl-based c gui library. wx 
and qt4 are gui application frameworks that include a gui library -- and 
much more that duplicate part of Python's stdlib. They, and consequently 
their Python wrappers, are too big. That is quite aside from the fact 
that the authors of the wrappers have good reason to not donate their 
code, but stay independent.


PyGui was designed as a gui library comparable to tkinter and a possible 
replacement. But according to the web page, it is still not completely 
ready for py 3 (the last update was July 2011).

http://www.cosc.canterbury.ac.nz/greg.ewing/python_gui/

I think a tkinter replacement should be written for at least 3.4+, so it 
can use the new 3.3 unicode implementation and use or at least integrate 
with the new 3.4 event loop that will be part of the planned new async 
library.


One test for any new gui library is whether idle can be rewritten in it. 
It heavily uses the tag features of the tk text widget.


TJR



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


Re: TypeError: unbound method add() must be called with BinaryTree instance as first argument (got nothing instead)

2013-05-18 Thread Terry Jan Reedy

On 5/18/2013 3:46 PM, Peter Otten wrote:

Dan Stromberg wrote:


python 2.x, python 3.x and pypy all give this same error, though jython
errors out at a different point in the same method.


By the way, 3.x doesn't have unbound methods, so that should work.


It does for this example (3.3.1)
 c = C()
 c.m()
__main__.C object at 0x033FC5F8
 C.m(c)
__main__.C object at 0x033FC5F8
 C.m(self=c)
__main__.C object at 0x033FC5F8



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


Re: Python for philosophers

2013-05-15 Thread Terry Jan Reedy

On 5/15/2013 9:17 PM, Tim Daneliuk wrote:


http://pvspade.com/Sartre/cookbook.html


Wikedly funny.


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


Re: Fwd: Python for philosophers

2013-05-14 Thread Terry Jan Reedy



2013/5/14 Steven D'Aprano steve+comp.lang.pyt...@pearwood.info
mailto:steve+comp.lang.pyt...@pearwood.info



 Python is not named after the snake, but after Monty Python the
British
 comedy troupe. And they picked their name because it sounded funny.


That does not mean they were unaware that Pythons are snakes.
requiring a slippery-sounding surname, they settled on Python


  http://en.wikipedia.org/wiki/Monty_Python
http://en.wikipedia.org/wiki/Monty_Python




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


Re: Writing a blog post on the new Enum.

2013-05-14 Thread Terry Jan Reedy

On 5/14/2013 3:52 AM, Chris Angelico wrote:

On Tue, May 14, 2013 at 9:40 AM, Fábio Santos fabiosantos...@gmail.com wrote:



http://fabiosantoscode.blogspot.pt/2013/05/pythons-new-enum-class.html


 class Text(unicode, Enum):
 one = u'one'
 two = u'two'
 three = u'three'


Is this supposed to be a quote? or your rewrite? or did Santos rewrite 
after you posted? The blog currently has a 3.x version of that.



That looks like Python 2 code. Are you backporting Enum to Py2
manually? AIUI the Python core won't be adding features like that to
2.7, and there won't be a 2.8, so PEP 435 will be Py3.4+ only. Or have
I misunderstood it?


As far as official CPython goes, Enum is 3.4+ only. I believe the module 
will continue to work on earlier 3.x and will remain externally 
available as a 3rd party module. Ethan said he plans to backport to 2.7 
so 2  3 code can use enums.



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


Re: Old version docs don't link to current version

2013-05-12 Thread Terry Jan Reedy

On 5/12/2013 10:12 AM, Chris Angelico wrote:

Not sure if this is an oversight or something deliberate... could be either.

 From http://docs.python.org/3.0/library/http.server.html there's no
link to the current docs, even though from
http://docs.python.org/3/library/http.server.html it's possible to
switch to 3.2 and then back to 3.3 (or to 2.7, but that fails and
redirects since http.server doesn't exist in 2.7). This wouldn't be
much of a bother, except that a Google search for 'python http.server'
(which is the way I normally pull up Python docs) landed me on /3.0/
instead of /3/.

Was this intentional, along the lines of not touching the old and
unsupported docs?


Cross referencing was added while 3.2 docs were still subject to 
revision. x.y docs are essentially frozen once the final x.y.z bugfix 
comes out.


Since I always enter the docs through docs.python.org/3/ (or /2/) typing 
just 'd' on Firefox history bar brings up both on the short history list 
to select. I then use module or general index.



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


Re: object.enable() anti-pattern

2013-05-12 Thread Terry Jan Reedy

On 5/12/2013 1:14 PM, Wayne Werner wrote:

On Fri, 10 May 2013, Gregory Ewing wrote:


Wayne Werner wrote:

You don't ever want a class that has functions that need to be called
in a certain order to *not* crash.


That seems like an overly broad statement. What
do you think the following should do?

  f = open(myfile.dat)
  f.close()
  data = f.read()


To clarify - you don't want a class that has functions that need to be
called in a certain order with *valid input* in order to not crash.

Exactly what does happen - a ValueError is raised because you're(*)
passing self into the file.read() function, and that input is invalid
input - specifically:

 ValueError: I/O operation on closed file

*where you actually means python, because when you call
`your_instance.method()`, it works effectively like a call to
`YourClass.method(your_instance)`


The new idiom
with open(myfile.dat) as f:
data = f.read()

partially encapsulates operations on the opened file before the 
automatic close. It is true however, that after the with statement, f in 
still uselessly bound to the closed file. (Well, you can check the mode, 
encoding, and other attributes, so not totally useless.) To completely 
encapsulate, one can end the block with 'del f'. I checked and this 
works. Since the external 'as x' name binding is optional, an internal 
reference to the context manager (the io.xxx instance) is kept in order 
to call the __exit__ method, and that is not affected by deleting the 
optional visible binding.


tjr


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


Re: object.enable() anti-pattern

2013-05-12 Thread Terry Jan Reedy

On 5/12/2013 12:48 PM, Wayne Werner wrote:


I'll share the anti-pattern that I've seen many times (not actually in
Python)

 class CoolPresenter:
 def __init__(self):
 self.view = None
 self.some_property = None
 self.other_property = None

 def initialize(self):
 self.view.disable()
 data = self.load_data()
 self.view.data = data
 self.view.enable()


 def reload(self):
 if self.view is None:
 raise NotInitializedError(Error: Please setup class)
 self.view.disable()
 data = self.load_data()
 self.view.data = data
 self.view.enable()



Then you would see code like this:

 presenter = CoolPresenter()
 presenter.view = CoolView()

This is just plain silly for a few reasons:

 - It's ambiguous. I don't know what's required for the CoolPresenter
   to function properly.

 - The temporal coupling mentioned earlier. I can create an instance of
   a class and then call a function (say `reload`) and then boom! My
   program crashes. There is *no possible* use case of this class where
   you can use it without a view.


Thank you for this examples. It makes Steven's point clearer than the 
'file object' example. The problem with the latter is that objectors 
could could point to file path objects, which are used to do some 
manipulations of files and directory entries on the storage device 
*without looking at the specific file data*. Such file data, as opposed 
to directory data, never enters the program data space and with smart 
enough devices, need not enter the CPU and its RAM. They could then 
confuse them with file access objects which are used to transfer 
specific data *between* files and program data space. The confusion is 
adied by the fact that file path objects are used to create file access 
objects. They do separate jobs and it seems that they are well kept 
separate, even if there are languages where file path objects can have 
file access functions turned on and off.



The motivation behind this anti-pattern that I've seen is the desire to
not have a constructor that does too much. So you end out with an
empty constructor and temporal coupling, and a terrible API that doesn't
clearly explain the requirements of the class. Your class constructor
should *require* everything that is necessary to have a stable state
when the class is created (i.e. you should be able to properly call any
function, set any property without an exception happening)

Why? Less bugs, easier to comprehend, change/update your code. Easier to
use the class.



--
Terry Jan Reedy



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


Re: Message passing syntax for objects | OOPv2

2013-05-12 Thread Terry Jan Reedy

On 5/12/2013 1:18 PM, Ned Batchelder wrote:

On 5/8/2013 10:39 PM, Mark Janssen wrote:

...The field needs re-invented and re-centered.[...]

For anyone who want to be involved.  See the wikiwikiweb -- a tool
that every programmer should know and use --  and these pages:
ComputerScienceVersionTwo and ObjectOrientedRefactored.


I've never understood why people use that site: the pages end up being
unintelligible cocktail-party noise-scapes with no hope of understanding
who is saying what, or in response to whom.


I certainly found it confusing that something responder and OP comments 
were in normal text and italic respectively, and sometimes the opposite, 
and maybe sometimes both in normal types.



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


Re: object.enable() anti-pattern

2013-05-09 Thread Terry Jan Reedy

On 5/9/2013 1:23 AM, Steven D'Aprano wrote:


Besides, this is not to denigrate the idea of a read() function that
takes a filename and returns its contents. But that is not an object
constructor. It may construct a file object internally, but it doesn't
return the file object, so it is completely unrelated to the scenario I
described.


At least a few stdlib modules that define classes *also* have such 
functions. They create an instance of the class, call one or more 
methods, and return the result of the method, discarding the instance. 
For instance, see the subprocess module, its POpen class, and module 
functions; or the timeit module, its Timer class, and functions.



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


Re: Forming a small python programming group

2013-05-09 Thread Terry Jan Reedy

On 5/9/2013 2:59 AM, kreta06 wrote:

Hi All,

I'm looking for one or two medium-advanced python programmers to
practice programming on a Windows 7 platform. In addition, any
interests in writing python code to query Microsoft SQL databases
(2005-2008) is also welcomed.

I've coded in python 2.7 and currently am trying to make the switch to
3.2 as there seem to be some changes to the syntax.


Start with 3.3 unless you *must* use 3.2. There is one less syntax 
change and a better unicode string implementation.




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


Re: cello library

2013-05-08 Thread Terry Jan Reedy

On 5/8/2013 6:01 AM, Chris Angelico wrote:

On Wed, May 8, 2013 at 7:39 PM, Mark Lawrence breamore...@yahoo.co.uk wrote:

Hi folks,

I thought some of you might find this interesting [link redacted]


Unredacted: http://libcello.org/


If this is a legit post, can you please elaborate on just _why_ we
would find it interesting? I'm leery of clicking random links like
that without at least some indication. It could be some cool Python
library, or it could be something relating to music, or it could be a
malicious site ready to compromise my browser and your Yahoo account
was compromised to send spam.


Legitimate request, like some I have made of others. Since I trust Mark:

Cello is a GNU99 C library which brings higher level programming to C.

Interfaces allow for structured design
Duck Typing allows for generic functions
Exceptions control error handling
Constructors/Destructors aid memory management
Syntactic Sugar increases readability
C Library means excellent performance and integration
...Cello is licensed under BSD3.

Partly inspired by Python, including this:

 /* with automatically closes file at end of scope. */
  with (file in open($(File, NULL), prices.bin, wb))) {
...
  }

An interesting question is whether it could be used to convert or 
rewrite Python to C.


__
Terry Jan Reedy


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


Re: Why do Perl programmers make more money than Python programmers

2013-05-07 Thread Terry Jan Reedy
On 5/7/2013 9:22 AM, jmfauth road forth on his dead hobbyhorse to hijack 
yet another thread:



# Py 3.3 ascii and non ascii chars

timeit.repeat(a = 'hundred'; 'x' in a)

[0.11426985953005442, 0.10040049292649655, 0.09920834808588097]

timeit.repeat(a = 'maçãé€ẞ'; 'é' in a)

[0.2345595188256766, 0.21637172864154763, 0.2179096624382737]


Python 3.3 is a language. Languages do not have timings.
CPython 3.3.0 is an implementation compiled and run under a particular 
OS and hardware. With respect to Unicode timings, especially for 
find/replace, it is obsolete. On my Win7 machine with fresh debug builds 
from the current repository, I see these times.


Python 3.3.1+ (default, May  7 2013, 14:03:12) [MSC v.1600 32 bit (Int
 from timeit import repeat
 repeat(a = 'hundred'; 'x' in a)
[0.19007337649622968, 0.190116721780754, 0.1900149679567562]
 repeat(a = 'maçaé??'; 'é' in a)
[0.20568874581187716, 0.20568782357178053, 0.20577051776710914]

Python 3.4.0a0 (default:32067784f198, May  7 2013, 13:59:10) [MSC v.1600
 from timeit import repeat
 repeat(a = 'hundred'; 'x' in a)
[0.1708080882915779, 0.17062978853956826, 0.1706740560642051]
 repeat(a = 'maçaé??'; 'é' in a)
[0.17612111348809734, 0.17562925210324565, 0.17549245315558437]

Note 1: debug builds are slower than install builds, especially for 
microbenchmarks with trivial statements. My installed 3.3.1 on a 
different machine has timings of about .1 for the ascii test. It is 
slower for the non-ascii test because the latest improvements were made 
after 3.3.1 was released.


Note 2: 3.4 has additional improvements that speed up everything, so 
that the 3.4 non-ascii time is faster that even the 3.3 ascii time.


Terry


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


Re: Get filename using filefialog.askfilename

2013-05-07 Thread Terry Jan Reedy

On 5/7/2013 4:27 PM, cheirasa...@gmail.com wrote:


file = filedialog.askopenfile ( mode... )


askopenfile is a convenience function that creates an Open dialog 
object, shows it, gets the name returned by the dialog, opens the file 
with that name, and returns an appropriate normal file object



to open a file with an open dialog box, OK. Made it.

How i get the name of the opened file?


file.name, (at least in 3.3), which in your example below is file.doc


print(file)

the output is: ..name=file.doc...mode=..encoding..  


This is the standard string representation of a file object. It is 
created from the various attributes of the file instance, including 
file.name.



How can i get the second member of 'file'?


Strings do not have fields. The second 'member', would be the second 
character, file[1], which is not what you want.



And i am unable to find a detailed reference to this object in the i.net


Use the Fine Manual. The entry for builtin open() function, which you 
should read to understand the 'open' part of askopenfile, directs you to 
the Glossary entry 'file object' which says There are actually three 
categories of file objects: raw binary files, buffered binary files and 
text files. Their interfaces are defined in the io module. The canonical 
way to create a file object is by using the open() function. The kind 
of file object you get is determined by the mode ('b' present or not), 
buffer arg, and maybe something else. You can look in the io chapter or 
use dir() and help() as John G. suggested.


Python programmers should really learn to use dir(), help(), and the 
manuls, including the index and module index.


--
Terry Jan Reedy


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


Re: Making safe file names

2013-05-07 Thread Terry Jan Reedy

On 5/7/2013 3:58 PM, Andrew Berg wrote:

Currently, I keep Last.fm artist data caches to avoid unnecessary API calls and 
have been naming the files using the artist name. However,
artist names can have characters that are not allowed in file names for most 
file systems (e.g., C/A/T has forward slashes). Are there any
recommended strategies for naming such files while avoiding conflicts (I 
wouldn't want to run into problems for an artist named C-A-T or
CAT, for example)? I'd like to make the files easily identifiable, and there 
really are no limits on what characters can be in an artist name.


Sounds like you want something like the html escape or urlencode 
functions, which serve the same purpose of encoding special chars. 
Rather than invent a new tranformation, you could use the same scheme 
used for html entities. (Sorry, I forget the details.) It is possible 
that one of the functions would work for you as is, or with little 
modification.


Terry



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


Re: First python program, syntax error in while loop

2013-05-06 Thread Terry Jan Reedy

On 5/6/2013 11:31 AM, Roy Smith wrote:

In article mailman.1361.1367847484.3114.python-l...@python.org,
Chris Angelico  ros...@gmail.com wrote:

On Mon, May 6, 2013 at 11:08 PM, Roy Smith r...@panix.com wrote:

On the other hand, I've long since given up trying to remember operator
precedence in various languages.  If I ever have even the slightest
doubt, I just go ahead and put in the extra parens.


If I ever have even the slightest doubt, I just go ahead and type
language operator precedence into a web search and check it :)


Well, that solves the problem once, and it solves it for me.  I figure
if I'm not 100% sure, then maybe other people aren't 100% sure either,
and my adding the extra parens helps them too.


If you keep the Python docs handy, on or off line, the Language manual 
Expressions chapter ends with this single page (but better formatted as 
a table than here). But I sometimes add parens for quickness or readability.


6.15. Operator precedence
The following table summarizes the operator precedences in Python, from 
lowest precedence (least binding) to highest precedence (most binding). 
Operators in the same box have the same precedence. Unless the syntax is 
explicitly given, operators are binary. Operators in the same box group 
left to right (except for comparisons, including tests, which all have 
the same precedence and chain from left to right — see section 
Comparisons — and exponentiation, which groups from right to left).


Operator Description
lambda Lambda expression
if – else Conditional expression
or Boolean OR
and Boolean AND
not x Boolean NOT
in, not in, is, is not, , =, , =, !=, == Comparisons, including 
membership tests and identity tests,

| Bitwise OR
^ Bitwise XOR
 Bitwise AND
,  Shifts
+, - Addition and subtraction
*, /, //, % Multiplication, division, remainder [5]
+x, -x, ~x Positive, negative, bitwise NOT
** Exponentiation [6]
x[index], x[index:index], x(arguments...), x.attribute Subscription, 
slicing, call, attribute reference
(expressions...), [expressions...], {key: value...}, {expressions...} 
Binding or tuple display, list display, dictionary display, set display


Footnotes

[1] While abs(x%y)  abs(y) is true mathematically, for floats it may 
not be true numerically due to roundoff. For example, and assuming a 
platform on which a Python float is an IEEE 754 double-precision number, 
in order that -1e-100 % 1e100 have the same sign as 1e100, the computed 
result is -1e-100 + 1e100, which is numerically exactly equal to 1e100. 
The function math.fmod() returns a result whose sign matches the sign of 
the first argument instead, and so returns -1e-100 in this case. Which 
approach is more appropriate depends on the application.
[2] If x is very close to an exact integer multiple of y, it’s possible 
for x//y to be one larger than (x-x%y)//y due to rounding. In such 
cases, Python returns the latter result, in order to preserve that 
divmod(x,y)[0] * y + x % y be very close to x.
[3] While comparisons between strings make sense at the byte level, they 
may be counter-intuitive to users. For example, the strings \u00C7 and 
\u0327\u0043 compare differently, even though they both represent the 
same unicode character (LATIN CAPITAL LETTER C WITH CEDILLA). To compare 
strings in a human recognizable way, compare using unicodedata.normalize().
[4] Due to automatic garbage-collection, free lists, and the dynamic 
nature of descriptors, you may notice seemingly unusual behaviour in 
certain uses of the is operator, like those involving comparisons 
between instance methods, or constants. Check their documentation for 
more info.
[5] The % operator is also used for string formatting; the same 
precedence applies.
[6] The power operator ** binds less tightly than an arithmetic or 
bitwise unary operator on its right, that is, 2**-1 is 0.5.




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


Re: (Learner-here) Lists + Functions = headache

2013-05-05 Thread Terry Jan Reedy

On 5/5/2013 8:59 PM, Bradley Wright wrote:

Hey guys and gals doing this tutorial(codecademy) and needed a bit help from 
the experienced.

I'm writing a function that takes a list(one they supply during runtime)
here's what my function is supposed to do


Do they supply an example so you can test both your comprehension and 
code? I think most specs given in natural language need such.



1. for each instance of the string fizz make a count
2. Finally return that count


Did you create an example problem to test your code? If not, do so.
Did you run your function with example data? If not, do so.


here's my code:

def fizz_cout(x):
 count = 0
 for item in x:
 while item == fizz:
 count += 1
 return count


Here is  hint as to some of what needs to be improved: this function 
will return either 1 or None. You should have discovered that by testings.


--
Terry Jan Reedy


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


Re: to a human - about 2to3

2013-05-01 Thread Terry Jan Reedy

On 5/1/2013 10:52 AM, Jennifer Butler wrote:


I will start teaching Python to my pupils shortly. I have been looking
for materials and have gathered a collection of programs. The problem is
they are written in v2 and I have v3 installed in my classroom. I read
about the 2to3 conversion program, but I can’t get it to work.


You might find this page
http://www.python.org/community/sigs/current/edu-sig/
and the education list itself. I am sure many programs useful in 
education have already been ported.


Many simple programs, of the sort used in beginner classes need minimal 
change. Oftem 'print x' to 'print(x)' is all that is needed. 2to3 will 
do that for you, once you learn how to use it, but I have not.  For the 
programs people post on the list, with just 1 or 2 prints, I make the 
change manually in the Idle editor before running. I often want to 
change other things as well, so no big deal.


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


Re: How do I encode and decode this data to write to a file?

2013-04-29 Thread Terry Jan Reedy

On 4/29/2013 5:47 AM, c...@isbd.net wrote:


case).  Here's the traceback:-




   File /usr/local/lib/python2.7/dist-packages/gallery/picture.py, line 361,

 in createPictureHTML file.write(.join(html).encode('utf-8'))
 UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 
783: ordinal not in range(128)


Generiric advice for anyone getting unicode errors:
unpack the composition producing the error
so that one can see which operation produced it.

In this case
s = .join(html)\
s = s.encode('utf-8')
file.write(s)

This also makes it possible to print intermediate results.
  print(type(s), s)  # would have been useful
Doing so would have immediately shown that in this case the error was 
the encode operation, because s was already bytes.
For many other posts, the error with the same type of message has been 
the print or write operation, do to output encoding issues, but that was 
not the case here.





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


Re: python.exe has stopped working when os.execl() runs on Windows 7

2013-04-28 Thread Terry Jan Reedy

On 4/27/2013 11:42 PM, cormog...@gmail.com wrote:


Is there the place to open a ticket for Python developers?


bugs.python.org


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


Re: Comparison Style

2013-04-27 Thread Terry Jan Reedy

On 4/27/2013 5:03 PM, Roy Smith wrote:

In article mailman.1077.1366944517.3114.python-l...@python.org,
  Chris Angelico ros...@gmail.com wrote:


If you switch the order of operands in that, the compiler won't help
you. Plus it reads wrong. So the convention is still
variable==constant.


I just found a nice example of putting the constant first.  I've just
done a whole bunch of ugly math to find some slice limits.  To make sure
they're sane, I'm writing:

 assert 5 = i  j  original_song_count

I can't think of any way to write that which would be as clean and easy
to read.


Chained comparisons like this are standard math notation, which is why 
Python 'does the right thing' with them.




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


Re: Nested For loop not running full

2013-04-26 Thread Terry Jan Reedy

On 4/26/2013 4:48 AM, inshu chauhan wrote:

Hello everyone,

I have this part of my code where I am trying to traverse over an image
by running a for loop for both x and y co-ordinate axis. But the loop is
terminating by just reading first pixel. Can think of a reason why this
is happening ?


*A* reason could be that segimage.height and .width are both 1. I would 
print them out to see what they are.




The code is:
for sy in xrange(0, segimage.height):
 for sx in xrange(0, segimage.width):
 if segimage[sy,sx] == (0.0, 0.0, 0.0):
 continue
 else:
 seg_color = segimage[sy,sx]
 blue = int(seg_color[0])
 green = int(seg_color[1])
 red = int(seg_color[2])
 reg_num = blue + 256 * green + 65536 * red
 for l in f:
 sp = l.split(,)
 if len(sp) == 14:
 print sy, sx  # for checking which pixel its
reading currently
 print reg_num, sp[0]  # for checking whats
happening
 if reg_num == int(sp[0].strip()):
 print reg_num, sp[0].strip() # for checking
whats happening
 classification = int(sp[13].strip())

The inside for loop is for reading a csv format file from which I am
extracting some information.

Thanks in Advance for your suggestions







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


Re: Libroffice PMT equivalent in python

2013-04-25 Thread Terry Jan Reedy

On 4/25/2013 6:46 AM, ஆமாச்சு wrote:

Hi,

Are there equivalent in any Python libraries that could match function
like PMT in libreoffice?

Refer: https://help.libreoffice.org/Calc/Financial_Functions_Part_Two#PMT


try the packages listed at
https://pypi.python.org/pypi?%3Aaction=searchterm=financesubmit=search


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


Re: My gui

2013-04-24 Thread Terry Jan Reedy

On 4/24/2013 1:53 PM, Chris “Kwpolska” Warrick wrote:


Please try fixing it and running it _outside of IDLE_, which is also
built in Tk


The default mode of Idle runs user code in a separate process. Editing 
tkinter code with Idle and running it (in the separate process) should 
be no problem.




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


Re: List Count

2013-04-23 Thread Terry Jan Reedy

On 4/23/2013 7:45 AM, Blind Anagram wrote:


I then wondered why count for lists has no limits


Probably because no one has asked for such, as least partly because it 
is not really needed. In any case, .count(s) is a generic method. It is 
part of the definition of a Sequence. It can also be implemented for 
non-sequence collections, such as a Tree class, that allow multiple 
occurrences of an item.


 whereas count for other objects (e.g. strings) has these.

Strings (of unicode or bytes) are exceptional in multiple ways.

--
Terry Jan Reedy


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


Re: List Count

2013-04-23 Thread Terry Jan Reedy

On 4/23/2013 12:57 PM, Blind Anagram wrote:


So, all I was doing in asking for advice was to check whether there is
an easy way of avoiding the slice copy,


And there is.


not because this is critical,
but rather because it is a pity to limit the performance because Python
forces a (strictly unnecessary) copy in order to perform a count within
a part of a list.


Python does not force that. You have been given several simple no-copy 
alternatives. They happen to be slower *with CPython* because of the 
speed difference between Python code and C code. If the same timing 
tests were done with any of the implementations that execute python code 
faster, the results would likely be different.


I thing str/byte/bytearray.count have more need for optional start,stop 
boundary parameters because a) people search in long texts and subtexts, 
more so I think that for other sequences, b) they search for substrings 
longer than 1 and hence c) the generic no-slice alternatives do not work 
for counting substrings.


That said, I do see that tuple/list.index have had start, stop 
paramaters added, so doing the same for .count is conceivable. I just do 
not remember anyone else asking for such. The use case must be very 
rare. And as I said in my other post, .count(x) applies to any 
collections, but start,stop would only apply to sequences.



In other words, the lack of a list.count(value, limit) function makes
Python less effective than it would otherwise be.


Untrue. The alternatives are just as *effective*.


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


Re: Nested iteration?

2013-04-23 Thread Terry Jan Reedy

On 4/23/2013 11:40 AM, Roy Smith wrote:

In reviewing somebody else's code today, I found the following
construct (eliding some details):

 f = open(filename)
 for line in f:
 if re.search(pattern1, line):
 outer_line = f.next()
 for inner_line in f:
if re.search(pattern2, inner_line):
 inner_line = f.next()


Did you possibly elide a 'break' after the inner_line assignment?


Somewhat to my surprise, the code worked.


Without a break, the inner loop will continue iterating through the rest 
of the file (billions of lines?) looking for pattern2 and re-binding 
inner-line if there is another line or raising StopIteration if there is 
not. Does this really constitute 'working'?


This is quite aside from issue of what one wants if there is no pattern1 
or if there is no line after the first match (probably not 
StopIteration) or if there is no pattern2.



I didn't know it was legal to do nested iterations over the same iterable


Yes, but the effect is quite different for iterators (start where the 
outer iteration left off) and non-iterators (restart at the beginning).


r = range(2)
for i in r:
for j in r:
print(i,j)
# this is a common idiom to get all pairs
0 0
0 1
1 0
1 1

ri= iter(range(3))
for i in ri:
for j in ri:
print(i,j)
# this is somewhat deceptive as the outer loop executes just once
0 1
0 2

I personally would add a 'break' after 'outer_line = next(f)', since the 
first loop is effectively done anyway at that point, and dedent the 
second for statement. I find to following clearer


ri= iter(range(3))
for i in ri:
break
for j in ri:
print(i,j)
# this makes it clear that the first loop executes just once
0 1
0 2

I would only nest if the inner loop could terminate without exhausting 
the iterator and I wanted the outer loop to then resume.


__
Terry Jan Reedy


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


Re: Is Unicode support so hard...

2013-04-21 Thread Terry Jan Reedy

On 4/20/2013 9:37 PM, rusi wrote:


I believe that the recent correction in unicode performance followed
jmf's grumbles


No, the correction followed upon his accurate report of a regression, 
last August, which was unfortunately mixed in with grumbles and 
inaccurate claims. Others separated out and verified the accurate 
report. I reported it to pydev and enquired as to its necessity, I 
believe Mark opened the tracker issue, and the two people who worked on 
optimizing 3.3 a year ago fairly quickly came up with two different 
patches. The several month delay after was a matter of testing and 
picking the best approach.



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


Re: suggestion for a small addition to the Python 3 list class

2013-04-21 Thread Terry Jan Reedy

On 4/21/2013 1:12 PM, Lele Gaifax wrote:

Robert Yacobellis ryacobel...@luc.edu writes:


I've noticed that the str join() method takes an iterable,


Specifically, it takes an iterable of strings. Any iterable can be made 
such iwth map(str, iterable) or map(repr, iterble).


 so in the

most general case I'm suggesting to add a join() method to every
Python-provided iterable (however, for split() vs. join()


.split *could* have been changed in 3.0 to return an iterator rather 
than a list, as done with map, filter, and others. An itersplit method 
*might* be added in the future.


 it would be

sufficient to just add a join() method to the list class).


That's the reasoning behind the rejection: to be friendly enough, you'd
need to include the join method in the sequence protocol, and
implement it on every sequence-like object (be it some kind of
UserList, or a generator, or an interator...)


Plus, only lists of strings can be joined, not generic lists.



This question carries several references to the various threads on the
subject:

http://stackoverflow.com/questions/493819/python-join-why-is-it-string-joinlist-instead-of-list-joinstring

ciao, lele.




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


Re: Include and lib files for Visual Studio?

2013-04-20 Thread Terry Jan Reedy

On 4/20/2013 4:59 PM, xuc...@gmail.com wrote:

I am looking for the Python include and lib files for windows. I have a c++ 
project that I am importing into Visual Studio 2010 (express) and it links 
python. I need the include and lib files for windows. Where can I get them?
I'd like to use python 3.3.1 if possible.

I found the msi on python.org but is says they don't include source. I am 
assuming there is a dev sdk or something similar but can't seem to find it.


If you want *everything*, clone hg.python.org/cpython (or something like 
that). PCBuild has Windows stuff, including VS .sln files.




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


Re: There must be a better way

2013-04-20 Thread Terry Jan Reedy

On 4/20/2013 8:34 PM, Tim Chase wrote:

In 2.x, the csv.reader() class (and csv.DictReader() class) offered
a .next() method that is absent in 3.x


In Py 3, .next was renamed to .__next__ for *all* iterators. The 
intention is that one iterate with for item in iterable or use builtin 
functions iter() and next().



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


Re: Feature Request: `operator.not_in`

2013-04-19 Thread Terry Jan Reedy

On 4/19/2013 10:27 AM, Matthew Gilson wrote:
) It seems to me that the operator module should have a `not_in` or

`not_contains` function.  It seems asymmetric that there exists a
`is_not` function which implements `x is not y` but there isn't a
function to represent `x not in y`.


There is also no operator.in.
There is operator.contains and operator.__contains__.
There is no operator.not_contains because there is no __not_contains__ 
special method. (Your point two, which I disagree with.)



2) I suspect this one might be a little more controversial, but it seems
to me that there should be a separate magic method bound to the `not in`
operator.


The reference manual disagrees.
The operator not in is defined to have the inverse true value of in.


 Currently, when inspecting the bytecode, it appears to me
that `not x in y` is translated to `x not in y` (this supports item 1
slightly).  However, I don't believe this should be the case.  In
python, `x  y` does not imply `not x = y` because a custom object can
do whatever it wants with `__ge__` and `__lt__` -- They don't have to
fit the normal mathematical definitions.


The reason for this is that the rich comparisons do not have to return 
boolean values, and do not for numarray arrays which, I believe, 
implement the operators itemwise.


 I don't see any reason why containment should behave differently.

'Design by analogy' is tricky because analogies often leave out 
important details. __contains__ *is* expected to return true/false.


 object.__contains__(self, item)
Called to implement membership test operators. Should return true 
if item is in self, false otherwise


--
Terry Jan Reedy


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


Re: Ubuntu package python3 does not include tkinter

2013-04-19 Thread Terry Jan Reedy

On 4/19/2013 1:17 PM, lcrocker wrote:

Am I mistaken in my belief that tkinter is a non-optional part of the
Python language?


Yes. The PSF CPython Windows installer makes installation of 
tcl/tk/tkinter optional. The build files will compile and build Python 
without tkinter and without other modules that depend on other c 
libraries (example, lzma). I believe one can build python 2 without 
unicode, which is much more 'core' than the Tkinter module.



I installed the python3 package on Ubuntu, and
tkinter is not included--it's an optional package python3-tk that
has to be installed separately. I reported this as a bug as was
summarily slapped down.


I hope it was done politely ;-).

Overall, Ubuntu is relatively advanced in moving to new versions. I 
believe I read that they are hoping to make 3.3 the default Python as 
soon as possible.



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


Re: Preparing sqlite, dl and tkinter for Python installation (no admin rights)

2013-04-18 Thread Terry Jan Reedy

On 4/18/2013 12:24 PM, James Jong wrote:

After compiling, you might want to run the test suite.


libtk8.6.so http://libtk8.6.so


I do not know that Python/_tkinter/tkinter has been very well tested, 
certainly not on all systems, with the newish tcl/tk 8.6, as opposed to 
8.5.z used for several years. There are 4 test/test_xxx files to be 
concerned about: something like test_tcl, test_tkinter, test_ttkxxx.


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


Re: The type/object distinction and possible synthesis of OOP and imperative programming languages

2013-04-16 Thread Terry Jan Reedy

On 4/16/2013 5:07 AM, Antoon Pardon wrote:

Op 16-04-13 05:17, Terry Jan Reedy schreef:

On 4/15/2013 10:32 PM, Steven D'Aprano wrote:

On Mon, 15 Apr 2013 20:52:58 -0400, Terry Jan Reedy wrote:





I will keep the above in mind if I write or review a patch. here are 4
non-subclassable builtin classes. Two are already documented. Bool in
one, forget which other. I believe it was recently decided to leave
the other two as is given the absence of any practical use case.


Why should there be a practical use case here?


As a practical matter, the change is non-trivial. Someone has to be 
motivated to write the patch to enable subclassing, write tests, and 
consider the effect on internal C uses of slice and stdlib Python used 
of slice (type() versus isinstance).



Since classes are in general subclassable,


if written in Python, but not if written in C.


I once had an idea of a slice-like class that I would have liked to
experiment with.


Did the idea actually require that instances *be* a slice rather than 
*wrap* a slice?


--
Terry Jan Reedy



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


Re: Preparing sqlite, dl and tkinter for Python installation (no admin rights)

2013-04-16 Thread Terry Jan Reedy

On 4/16/2013 10:30 AM, rosoloum wrote:

I do not have admin rights on my machine


The answer to your question may depend on the OS (linux), distribution 
(many), and version.



What about `_tkinter` and  `dl`? How can I have them ready for the Python
installer?


Building _tkinter (a Python C-coded module) requires tcl/tk and header 
files. Some distros have a separate python sdk kit with the headers not 
included with tcl/tk.



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


Re: a couple of things I don't understand wrt lists

2013-04-16 Thread Terry Jan Reedy

On 4/16/2013 11:37 AM, aaB wrote:


I represent the CA's rule with a list of integers, of value 1 or 0.
Here is the function I use to generate the list:

def get_rule(rulenum):
   rule = []
   while rulenum  0:
 rule.append(rulenume % 2)
 rulenum /= 2


divmod(rulenum) will return both the quotient and remainder at one time


   while len(rule)  8:
 rule.append(0)
   rule.reverse()
   return rule


In versions of Python with builtin bin(), you could write

def get_rule(rulenum):
b = bin(rulenum)[2:]  #
return [0]*(8-len(b)) + [int(i) for i in b]

To know Python decently well, you should understand all of that syntax.


rule = getrule(int(8))
print rule
[0, 0, 0, 0, 1, 0, 0, 0]



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


Re: The node.js Community is Quietly Changing the Face of Open Source

2013-04-16 Thread Terry Jan Reedy

On 4/16/2013 12:02 PM, Rodrick Brown wrote:

I came across this article which sums up some of the issues I have with
modern programming languages. I've never really looked at Javascript for
anything serious or Node itself but I found this article really
informational.

The “Batteries included” philosophy of Python was definitely the right
approach during the mid 90’s and one of the reasons that I loved Python
so much; this was a time before modern package management, and before it
was easy to find and install community-created libraries.  Nowadays


Python gets used in places like corporations and schools where one 
cannot simply install stuff off the net, but must fill out a form asking 
permission, or maybe not ask at all.



though I think it’s counter-productive.  Developers in the community
rarely want to bother trying to compete with the standard library, so
people are less likely to try to write libraries that improve upon it.


Except that there is competition for many modules. That said, there are 
old modules that probably would not be added today, and some the dev 
would like to remove. (Some were for 3.0.)



http://caines.ca/blog/programming/the-node-js-community-is-quietly-changing-the-face-of-open-source/


The irony is that the author goes on to say that the node.js community 
'works' because they all use the same infrastructure battery: git and 
git-hub ;-).


--
Terry Jan Reedy


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


Re: The type/object distinction and possible synthesis of OOP and imperative programming languages

2013-04-16 Thread Terry Jan Reedy

On 4/16/2013 1:29 PM, Ethan Furman wrote:

On 04/16/2013 01:25 AM, Serhiy Storchaka wrote:

On 16.04.13 07:46, Ian Kelly wrote:

On Mon, Apr 15, 2013 at 9:17 PM, Terry Jan Reedy tjre...@udel.edu
wrote:

I will keep the above in mind if I write or review a patch. here are 4
non-subclassable builtin classes. Two are already documented. Bool
in one,
forget which other. I believe it was recently decided to leave the
other two
as is given the absence of any practical use case.


The four are bool, NoneType, slice and ellipsis, I believe.


-- import builtins
-- for n in dir(builtins):
... if type(getattr(builtins, n)) is type:
... try:
... t = type(n, (getattr(builtins, n),), {})
... except TypeError as e:
... print(e)
...
type 'bool' is not an acceptable base type
type 'memoryview' is not an acceptable base type
type 'range' is not an acceptable base type
type 'slice' is not an acceptable base type


Well that bumps our count to five then:

-- NoneType = type(None)
-- NoneType
class 'NoneType'
-- class MoreNone(NoneType):
...   pass
...
Traceback (most recent call last):
   File stdin, line 1, in module
TypeError: type 'NoneType' is not an acceptable base type


'NoneType' is not a builtin name in builtins, which is precisely why you 
accessed it the way you did ;-). From issue 17279 (for 3.3):


Attached subclassable.py produces these lists:
Among named builtin classes, these cannot be subclassed:
bool, memoryview, range, slice,
Among types classes, these can be subclassed:
ModuleType, SimpleNamespace,



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


Re: Missing decimals in the code - some suggestions?

2013-04-16 Thread Terry Jan Reedy

On 4/16/2013 2:02 PM, hmjelte...@gmail.com wrote:

Hi!

I am using ystockquote with the following code:

def get_historical_prices(symbol, start_date, end_date):
 
 Get historical prices for the given ticker symbol.
 Date format is 'MMDD'

 Returns a nested list.
 
 url = 'http://ichart.yahoo.com/table.csv?s=%s;' % symbol + \
   'd=%s' % str(int(end_date[4:6]) - 1) + \
   'e=%s' % str(int(end_date[6:8])) + \
   'f=%s' % str(int(end_date[0:4])) + \
   'g=d' + \
   'a=%s' % str(int(start_date[4:6]) - 1) + \
   'b=%s' % str(int(start_date[6:8])) + \
   'c=%s' % str(int(start_date[0:4])) + \
   'ignore=.csv'
 days = urllib.urlopen(url).readlines()
 data = [day[:-2].split(',') for day in days]
 return data

This code prints the data, but only 2 decimals. I need to print out 4 decimals.


As far as I know, prices are only defined to the nearest penny* (2 
decimals) so I don't know what more you expect.


*Not too long ago, prices were in 1/8ths of a dollar. Market makers 
complained about decimalization because it would squeeze the spread that 
they profited from -- which it did.



print ystockquote.get_historical_prices('EURUSD=X','20120101','20120301')

Some suggestions?



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


Re: Understanding Boolean Expressions

2013-04-16 Thread Terry Jan Reedy

[2nd try, quotation a bit messed up]

On 4/16/2013 6:19 PM, Bruce McGoveran wrote:

 Hello.  I am new to this group.  I've done a search for the topic
 about which I'm posting, and while I have found some threads that are
 relevant, I haven't found anything exactly on point that I can
 understand.  So, I'm taking the liberty of asking about something
 that may be obvious to many readers of this group.

 The relevant Python documentation reference is:
 http://docs.python.org/2/reference/expressions.html#boolean-operations.

 I'm trying to make sense of the rules of or_test, and_test, and
 not_test that appear in this section.  While I understand the
 substance of the text in this section,


The substance is that 1) 'not' binds tighter than 'and' binds tigher 
than 'or' and 2) 'and' and 'or' both associate left to right in the 
normal manner so that 'a op b op c' == '(a op b) op c'.


 it is the grammar definitions themselves that confuse me.

The techinical details reflect the fact that Python's grammar is ll(1) 
(top-down, parsed by recursive descent) rather than lr(1) (bottom-up). 
The latter (in lalr(1) form) is what yacc, etc use and might be more 
familiar to you.


 For example, I am not clear how an or_test can be an and_test.

or_test  ::=  and_test | or_test or and_test

The second option expresses the associativity rule, but more is needed 
to get out of infinite regress. Substituting the second rule into second 
rule gives


or_test = (or_test 'or' and_test) 'or' and_test

and so on. At some point, one must replace or_test with and_test to get 
an 'or' of ands. Similarly, an and_test must resolve to an 'and' of nots.


 Moreover, if I follow the chain of non-terminal references, I move
 from or_test, to and_test, to nt_test, to comparison.  And when I
 look at the definition for comparison, I seem to be into bitwise
 comparisons.  I cannot explain this.

Eventually the chain takes one to primaries, which include things like 
literals and identifiers.


 Perhaps an example will help put my confusion into more concrete 
terms.  Suppose I write the expression if x or y in my code.  I 
presume this is an example of an or_test.


Yes.

 Beyond that, though, I'm  not sure whether this maps to an and_test 
(the first option on the  right-hand side of the rule) or to the or_test 
or and_test option (the second on the right-hand side of the rule).


The second. Then the or_test on the left also maps to an and_test. Each 
and_test eventually resolves to 'identifier', specifically 'x' and 'y'.


--
Terry Jan Reedy


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


Re: Cross-compiling Python for ARM?

2013-04-15 Thread Terry Jan Reedy

On 4/15/2013 11:20 AM, Gilles wrote:

Hello

I tried running uWSGI on an ARM-based appliance, but it fails.

Apparently, it could be due to the official Python 2.6.6 interpreter
in the depot not being compiled the way uWSGI expects it to be:

./configure --enable-shared; make; make install;
www.raspberrypi.org/phpBB3/viewtopic.php?f=32t=15370

I see Python mentioned in /usr/lib and /usr/share, and was wondering
if all it'd take to solve this issue, is just to cross-compile the
interpreter and the rest is just CPU-agnostic Python scripts.

Just in case, here's the output:
www.pastebin.com/wJHjBrfn


I believe some cross-compile support was added to 2.7.4 but I do not 
know the exact nature.



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


Re: The type/object distinction and possible synthesis of OOP and imperative programming languages

2013-04-15 Thread Terry Jan Reedy

On 4/15/2013 1:43 PM, Antoon Pardon wrote:


$ python3
Python 3.2.3 (default, Feb 20 2013, 17:02:41)
[GCC 4.7.2] on linux2
Type help, copyright, credits or license for more information.
  class vslice (slice):
...   pass
...
Traceback (most recent call last):
   File stdin, line 1, in module
TypeError: type 'slice' is not an acceptable base type


It seems types and classes are still not mere synonyms.


Some builtin classes cannot be subclassed. There is an issue to document 
which better. That does not mean that it is not a class.



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


Re: The type/object distinction and possible synthesis of OOP and imperative programming languages

2013-04-15 Thread Terry Jan Reedy

On 4/15/2013 10:32 PM, Steven D'Aprano wrote:

On Mon, 15 Apr 2013 20:52:58 -0400, Terry Jan Reedy wrote:



Some builtin classes cannot be subclassed. There is an issue to document
which better. That does not mean that it is not a class.



I think it is also important to document whether that is a language
feature, or a mere restriction of the implementation. There is an
important distinction to be made between:

In CPython, you cannot subclass slice or FunctionType. Other Pythons may
have more, or fewer, restrictions.

and:

No language that calls itself Python is permitted to allow slice and
FunctionType to be subclassable.


If I had a say in this, I would vote for the first case, with the
possible exception of documented singleton types like NoneType and bool.


I will keep the above in mind if I write or review a patch. here are 4 
non-subclassable builtin classes. Two are already documented. Bool in 
one, forget which other. I believe it was recently decided to leave the 
other two as is given the absence of any practical use case.



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


Re: The type/object distinction and possible synthesis of OOP and imperative programming languages

2013-04-14 Thread Terry Jan Reedy
Note: cross-posting to mailing lists does not work well. Hence the reply 
only to python-list and the gmane mirror.


On 4/14/2013 11:48 PM, Mark Janssen wrote:


Python is an interpreted language.


I consider this a useless or even deceptive statement. Python is an 
object-based algorithm language. The CPython implementation (currently) 
*compiles* Python code to a virtual machine bytecode, similar to Java 
bytecode. This could change. Jython translates to Java, which is then 
compiled to Java bytecode. Do you call Java an 'interpreted' language? 
There are compilers that compile Python to the same 'object code' that C 
is compiled to.


Since 2001, Python's has migrated towards a pure Object model.

It migrated towards a pure class model.


model (ref: http://www.python.org/download/releases/2.2/descrintro/).
Prior to then, it had both types and classes and these types were
anchored to the underlying C code and the machine/hardware
architecture itself.


I started with Python 1.3 and I have no idea what you mean by this. I 
think you are heavily confusing Python the language and CPython the 
implementation.



After the 2001 type/class unification , it
went towards Alan Kay's ideal of everything is an object.


Everything has always been an object with value and identity.

This stands in contrast to the assemble/C model that everything (except 
registers) is a block of linear memory with an address.



My question is:  Is there something in the Computer Science literature
that has noticed this distinction/development in programming language
design and history?


To me, there should be, since this is a fundamental distinction in data 
models. I think the biggest problem in shifting from C to Python is 
'getting' the data model difference. For Lispers, the difference is the 
syntax.


--
Terry Jan Reedy


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


Re: API design for Python 2 / 3 compatibility

2013-04-13 Thread Terry Jan Reedy

On 4/13/2013 12:36 PM, Stefan Schwarzer wrote:

Hello,

I'm currently changing the FTP client library ftputil [1]
so that the same code of the library works with Python
2 (2.6 and up) and Python 3. (At the moment the code is for
Python 2 only.) I've run into a API design issue where I
don't know which API I should offer ftputil users under
Python 2 and Python 3.

[1] http://ftputil.sschwarzer.net/

Some important background information: A key idea in ftputil
is that it uses the same APIs as the Python standard library
where possible. For example, with ftputil you can write code
like this:

   with ftputil.FTPHost(host, user, password) as ftp_host:
   # Like `os.path.isdir`, but works on the FTP server.
   if ftp_host.path.isdir(hello_dir):
   # Like `os.chdir`, but works on the FTP server.
   ftp_host.chdir(hello_dir)
   # Like the `open` builtin, but opens a remote file.
   with ftp_host.open(new_file, w) as fobj:
   # Like `file.write` and `file.close`
   fobj.write(Hello world!)
   fobj.close()

Since most of Python 2's and Python 3's filesystem-related
APIs accept either bytes and character strings (and return
the same type if they return anything string-like at all),
the design here is rather clear to me.

However, I have some difficulty with ftputil's counterpart
of the `open` builtin function when files are opened for
reading in text mode. Here are the approaches I've been
thinking of so far:

* Approach 1

   When opening remote text files for reading, ftputil will
   return byte strings from `read(line/s)` when run under
   Python 2 and unicode strings when run under Python 3.

 Pro: Each of the Python versions has ftputil behavior
 which matches the Python standard library behavior of
 the respective Python version.

 Con: Developers who want to use ftputil under Python 2
 _and_ 3 have to program against two different APIs since
 their code inherits ftputil's duality.

 Con: Support for two different APIs will make the
 ftputil code (at least a bit) more complicated than just
 returning unicode strings under both Python versions.

* Approach 2

   When opening remote text files for reading, ftputil will
   always return unicode strings from `read(line/s)`,
   regardless of whether it runs under Python 2 or Python 3.

 Pro: Uniform API, independent on underlying Python
 version.

 Pro: Supporting a single API will result in cleaner code
 in ftputil than when supporting different APIs (see
 above).

 Con: This approach might break some code which expects
 the returned strings under Python 2 to be byte strings.

 Con: Developers who only use Python 2 might be confused
 if ftputil returns unicode strings from `read(line/s)`
 since this behavior doesn't match files opened with
 `open` in Python 2.

Which approach do you recommend and why do you prefer that
approach? Are there other approaches I have overlooked? Do
you have other suggestions?


Approach 2 matches (or should match) io.open, which became builtin open 
in Python 3. I would simply document that ftp_host.open mimics io.open 
in the same way that ftp_host.chdir, etcetera, match os.chdir, etc. Your 
principle will remain intact.


Anyone writing *new* Py 2 code with any idea of ever running on Py 3 
should be using io.open anyway. That is why it was backported. You might 
be able to reuse some io code or subclass some io classes for your 
implementation.



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


Re: shutil.copyfile is incomplete (truncated)

2013-04-12 Thread Terry Jan Reedy

On 4/12/2013 3:32 AM, Chris Angelico wrote:

On Fri, Apr 12, 2013 at 4:25 PM, Rob Schneider rmsc...@gmail.com wrote:



The close method is defined and flushing and closing a file, so

it should not return until that's done.



What command are you using to create the temp file?




re command to write the file:
f=open(fn,'w')
... then create HTML text in a string
f.write(html)
f.close


Hold it one moment... You're not actually calling close. The file's
still open. Is that a copy/paste problem, or is that your actual code?

In Python, a function call ALWAYS has parentheses after it. Evaluating
a function's name like that returns the function (or method) object,
which you then do nothing with. (You could assign it someplace, for
instance, and call it later.) Try adding empty parens:

f.close()

and see if that solves the problem. Alternatively, look into the
'with' statement and the block syntax that it can give to I/O
operations.


I say *definitely* use a 'with' statement. Part of its purpose is to 
avoid close bugs.



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


Re: name lookup failure using metaclasses with unittests

2013-04-12 Thread Terry Jan Reedy

On 4/12/2013 3:17 AM, Ulrich Eckhardt wrote:

Am 11.04.2013 10:19, schrieb Steven D'Aprano:

if sys.version = '3':


Use sys.version_info = (3,), otherwise your code breaks when upgrading
to Python 10 and greater. ;^)



The second question that came up was if there is a way to keep a
metaclass defined inside the class or if the only way is to provide it
externally. [...]


Not in general, since the metaclass has to exist independently of the
class.


Thanks for your explanations, they are appreciated.


  The class is an instance of your metaclass. That means that the
  metaclass must exist first, so it can be instantiated when you
  define the class.

I don't like the approach to define the code to post-process a class
before defining the class. It's a bit like top-posting, it messes up the
reading order. Since I really intend to post-process the class, it seems
that metaclasses are simply not the right tool.


Using a post-processing object as a metaclass or decorator necessarily 
requires predefinition. Such objects are usually used more than once.


For one-off postprocessing, I probably would not bother.


At the moment, this leaves me with two options:

1. post-process the class

class X:
 pass
# attach constants to clas X
for i in (1, 2, 3):
 setattr(X, 'f{}' % i, i)

2. generate code inline

class Y: pass
 # generate constants in local (class-)namespace
 for i in (1, 2, 3):
 locals()['f{}' % i] = i


Mutating class locals() currently works in CPython, but is explicitly 
not guaranteed to work by the language definition.



In both cases, variables (loop variable 'i') are leaked into the
surrounding namespace, which is kind-of ugly. The second approach also
seems a bit hackish and I can't use the class-in-definition there, which
is limiting when you want to attach e.g. constants of type X to X.



Also PEP 3115 Metaclasses in Python 3000[2] seems to
consider postprocessing of a class definition as better handled by a
class decorator, which is something I haven't looked at yet.


Generally, class decorators are less brain-melting than metaclasses.


Alas, they also need to be defined before the class, messing with the
mentioned order of declaration. They can be used to call a class
function though which then does the necessary postprocessing...

3. post-process the class triggered with decorator

def postprocess_class(cls):
 invoke postprocess() on the decorated object
 cls.postprocess()
 del cls.postprocess
 return cls

@postprocess_class
class Z:
 @classfunction
 def postprocess(cls):
 # attach constants to class
 for i in (1, 2, 3):
 setattr(cls, 'f{}' % i, i)


I guess I'll stay with variant 1 for now, since it requires the least
amount of code and the least amount of questions from other developers
here.



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


Re: SimpleHTTPRequestHandler used with HTTP/1.1 hangs after the second resource on a page.

2013-04-12 Thread Terry Jan Reedy

On 4/12/2013 4:46 PM, Piotr Dobrogost wrote:

Hi!

I'd like to bring your attention to the question titled Use HTTP/1.1
with SimpleHTTPRequestHandler at
http://stackoverflow.com/q/15839718/95735 which reads; When I use


I find the doc slightly confusing. The SO code uses BaseHTTPServer. The 
doc says Usually, this module isn’t used directly, On the other hand, 
SimpleHTTPServer only defines a request handler and not a server itself.



HTTP/1.1 with SimpleHTTPRequestHandler, loading a page that pulls in
other resources will hang after the second resource. and there's a


What does 'hang' mean? Does the page get displayed? If so, 
server.serve_forever is supposes to 'hang'.



tiny test showing the problem. It's hard to believe that
SimpleHTTPServer doesn't handle such a simple task, does it? If I
checked correctly code is stuck in handle_one_request() method at
line 370 of server.py
(http://hg.python.org/cpython/file/d9893d13c628/Lib/http/server.py#l370)
but I can't see what's wrong. Any ideas?


The SO post says

class MyRequestHandler(SimpleHTTPRequestHandler):
#protocol_version = HTTP/1.0   # works
protocol_version = HTTP/1.1   # hangs

so this should be some sort of clue. The code says

569 # The version of the HTTP protocol we support.
570 # Set this to HTTP/1.1 to enable automatic keepalive
571 protocol_version = HTTP/1.0

The only substantive code I found using protocol_version (in the CPython 
default branch you linked to) is


300 if version_number = (1, 1) and self.protocol_version = HTTP/1.1:
301 self.close_connection = 0

331 elif (conntype.lower() == 'keep-alive' and
332 self.protocol_version = HTTP/1.1):
333 self.close_connection = 0
334 # Examine the headers and look for an Expect directive
335 expect = self.headers.get('Expect', )
336 if (expect.lower() == 100-continue and
337 self.protocol_version = HTTP/1.1 and
338 self.request_version = HTTP/1.1):
339 if not self.handle_expect_100():
340 return False

I would re-test with the recently released 3.3.1 (and/or 2.7.4) to make 
sure nothing has changed


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


Re: Python module vs library

2013-04-09 Thread Terry Jan Reedy

On 4/9/2013 5:58 AM, k.lykour...@gmail.com wrote:

Hi, what is the difference between python module and library ?


They are in different categories. A Python module is a namespace (a 
mapping of names to objects) created by running Python code as a main 
module or by import statements within Python code (or by executing 
import functions within a Python interpreter). A library in general is a 
collection of functions and classes used by multiple applications. A 
Python library is composed of Python modules, packages, and collections 
of such.



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


Re: newbie question about confusing exception handling in urllib

2013-04-09 Thread Terry Jan Reedy

On 4/9/2013 7:41 AM, cab...@gmail.com wrote:

Hi,

I have been using Java/Perl professionally for many years and have been trying 
to learn python3 recently. As my first program, I tried writing a class for a 
small project, and I am having really hard time understanding exception 
handling in urllib and in python in general...
Basically, what I want to do is very simple,


Very funny ;-). What you are trying to do, as your first project, is 
interact with the large, multi-layered, non=deterministic monster known 
as Internet, with timeout handling, through multiple layers of library 
code. When it comes to exception handling, this is about the most 
complex thing you can do.



try to fetch something tryurllib.request.urlopen(request), and:
   - If request times out or connection is reset, re-try n times
   - If it fails, return an error
   - If it works return the content.

But, this simple requirement became a nightmare for me. I am really confused 
about how I should be checking this because:
   - When connection times out, I sometimes get URLException with reason 
field set to socket.timeout, and checking (isinstance(exception.reason, socket.timeout)) 
works fine
   - But sometimes I get socket.timeout exception directly, and it has no 
reason field, so above statement fails, since there is no reason field there.


If you are curious why the different exceptions for seemingly the same 
problem, you can look at the printed traceback to see where the 
different exceptions come from. Either don't catch the exceptions, 
re-raise them, or explicitly grab the traceback (from exc_info, I believe)



   - Connection reset is a totally different exception
   - Not to mention, some exceptions have msg / reason / errno fields but some 
don't, so there is no way of knowing exception details unless you check them 
one by one. The only common thing I could was to find call __str__()?


The system is probably a bit more ragged then it might be if completely 
re-designed from scratch.



   - Since, there are too many possible exceptions, you need to catch 
BaseException (I received URLError, socket.timeout, ConnectionRefusedError, 
ConnectionResetError, BadStatusLine, and none share a common parent). And, 
catching the top level exception is not a good thing.


You are right, catching BaseException is bad. In particular, it will 
catch KeyboardInterrupt from a user trying to stop the process. It is 
also unnecessary as all the exceptions you want to catch are derived 
from Exception, which itself is derived from BaseException.



So, I ended up writing the following, but from everything I know, this looks 
really ugly and wrong???

 try:
 response = urllib.request.urlopen(request)
 content = response.read()
 except BaseException as ue:


except Exception as ue:


 if (isinstance(ue, socket.timeout) or (hasattr(ue, reason) and 
isinstance(ue.reason, socket.timeout)) or isinstance(ue, ConnectionResetError)):
 print(REQUEST TIMED OUT)

or, something like:

 except:


except Exception:


 (a1,a2,a3) = sys.exc_info()
 errorString = a2.__str__()
 if ((errorString.find(Connection reset by peer) = 0) or 
(errorString.find(error timed out) = 0)):


--
Terry Jan Reedy


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


Re: The usage of -m option of python

2013-04-08 Thread Terry Jan Reedy

On 4/8/2013 10:50 AM, Albert van der Horst wrote:

In article mailman.3484.1363662214.2939.python-l...@python.org,
Terry Reedy  tjre...@udel.edu wrote:

On 3/18/2013 5:17 PM, Peng Yu wrote:

Hi,

I don't quite understand how -m option is used. And it is difficult to
search for -m in google. Could anybody provide me with an example on
how to use this option?


python -m test
at a command line runs the regression tests in the test package
python -m test -v test_difflib
runs test.test_difflib in verbose mode.


I get for both :
/usr/bin/python: test is a package and cannot be directly executed.

What gives?

(Official stable Debian distribution. Python 2.7)


For me, 3.3 is default Python.

Look in the 2.7 doc for 'test' and I believe it will tell you that you 
need to write 'test.regrtest'.


tjr



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


Re: Interactive development in Python à la Smalltalk?

2013-04-08 Thread Terry Jan Reedy

On 4/8/2013 4:33 AM, Bienlein wrote:

Hello,

I'm absolutely new to Python, just looked at the language description
for the first time. The first thought that came to my mind was
whether you can program  in Python in an interactive programming
style, i.e. I can change code in the debugger which becomes
immediately effective (no edit-compile loop) and I can also send
messages to objects visible inside the debugger.


The CPython interpreter has both a 'batch' mode (run code in a file) and 
an interactive mode (run code typed in response to a prompt). It also 
has a '-i' option to run code in batch mode and then switch to 
interactive mode so one can interrogate visible objects and call functions.


The Idle IDE has editor windows linked to an interactive shell. When you 
run code in the editor window, it saves and runs it with the -i option 
so you can interactive with the results in the Shell. Compiling edited 
text to bytecode is typically so fast (well under a second) as to not be 
an issue.



Then Python could become my replacemenet for my dearly missed
Smalltalk, which to my great grief meanwhile really has become quite
dead, I fear. In Smalltalk you can open up an inspector window (e.g.
you don't have to get into debug mode), inspect objects in it and
evaluate code in it, send messaages to objects. I guess this cannot
be done in Python out of the box. But if changes made in the debugger
became immediately effective, this would be interactive enough for my
purposes.


Idle also has a debugger window that does some of that, though it works 
better on non-Windows OSes. I have never actually used it.


---
Terry Jan Reedy


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


Re: How do I tell if I'm running under IDLE?

2013-04-06 Thread Terry Jan Reedy

On 4/5/2013 5:30 AM, Steven D'Aprano wrote:


I'm looking for an official way to tell what interpreter (if any) is
running, or at least a not-too-horrible unofficial way.


The interpreters distributed by PSF identify themselves on startup, as 
least in interactive mode, by displaying a line like Python 3.3.0+ 
(default, Mar 30 2013, 17:36:11) [MSC v.1600 32 bit (Intel)] on win32
The version available as sys.version, sys.hexversion, and 
sys._version(). The platform is available as sys.platform. The compiler 
and compile date are not officially available.


But you seem not to be actually asking 'what interpreter is running' but 
'who started the interpreter' and 'is the interpreter i/o connected to a 
text-mode OS console or to a gui program, such as IDLE, more or less 
simulating an OS console.


There is no official way because it should not matter to a running 
program. It is the goal of at least some IDLE developers to make the 
connection to the IDLE shell as transparent as possible to Python code, 
so that it matters as little as possible*. This is one reason for the 
shift from running user code in the same process and interpreter 
instance as Idle to running user code in a separate process with its own 
interpreter instance.


* There are current tracker issues about making this true. We really do 
not want people to have to write conditional code, unless it is to work 
around a console problem if Idle is not being used ;-).


If you have an issue not already covered on the tracker, I am curious 
what it is.



Googling comes up with a number of hacks for detecting IDLE. Some of them
are terrible. For example, I can't believe that somebody actually
suggested this:

if len(sys.modules)  20:
 print running under IDLE


This is based on the fact that if running in the same process, there are 
a lot more imported modules and if running in a separate process, there 
are at least a few more imported modules to set up the rpc connection. I 
do not know that '20' is particularly reliable, even on startup.



This one is better, but still not exactly what I consider great:


Why not, if is works for all Idle versions so far? The irreducible 
effect of any non-OS-console environment is to override the normal i/o.



sys.stdin.__class__.__module__.startswith('idlelib')


'idlelib' in sys.stdin.__class__.__module__' is possibly more future-proof.


Ideally, I'd like to detect any arbitrary environment such as Spyder,
IPython, BPython, etc., but will settle for just IDLE.


I expect that looking as sys.stdin in someway should work for all.

--
Terry Jan Reedy


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


Re: problem in running a basic code in python 3.3.0 that includes HTML file

2013-04-04 Thread Terry Jan Reedy

On 4/4/2013 3:08 PM, Satabdi Mukherjee wrote:

i have written this code and i need to run this file

def CreateEvent(str):


Using the builtin name 'str' as a parameter name is a bad idea.
Use 's' or 'string' or something instead.


This prints a passed string into this function;


The line above has to be indented. Leave off the trailing ';'


print str;


This is not valid in Python 3, where print() is a function
This line would have to be 'print(s)'. However, the function as written 
is senseless; just call print() directly.



return;


And empty return at the end does nothing. There is already an implicit 
'return None' at the end of every function.



CreateEvent (print'''


delete 'print' -- it is another syntax error.


content-type: text/html

  html
  head
  title the list of all possible events that can be notified by our system 
/title
  /head
  body
form
input type=checkbox name=tsunami value=tsunamitsunamibr
input type=checkbox name=earthquake value=earthquakeearthquakebr
input type=checkbox name=volcano value=volcanovolcanobr
input type=checkbox name=hurricane value=hurricanehurricanebr
input type=checkbox name=sinkholes value=sinkholessinkholesbr
input type=checkbox name=tornado value=tornadotornadobr
input type=checkbox name=landslide value=landslidelandslidebr
input type=checkbox name=downburst value=downburstdownburstbr
/form

input type=submit value=Submit
/body
/html
''')


--
Terry Jan Reedy



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


Re: Performance of int/long in Python 3

2013-04-03 Thread Terry Jan Reedy

On 4/3/2013 1:32 AM, Steven D'Aprano wrote:

On Wed, 03 Apr 2013 14:31:03 +1100, Neil Hodgson wrote:


 Sorting a million string list (all the file paths on a particular
computer) went from 0.4 seconds with Python 3.2 to 0.78 with 3.3 so
we're out of the 'not noticeable by humans' range. Perhaps this is still
a 'micro-benchmark' - I'd just like to avoid adding email access to get
this over the threshold.


What system *and* what compiler and compiler options. Unless 3.2 and 3.3 
are both compiler with the same compiler and settings, we do not know 
the source of the difference.



I cannot confirm this performance regression. On my laptop (Debian Linux,
not Windows), I can sort a million file names in approximately 1.2
seconds in both Python 3.2 and 3.3. There is no meaningful difference in
speed between the two versions.


I am guessing that Neil's undisclosed system (that I can see) is 
Windows, since other benchmarks have been more different on Windows than 
on *nix. Given that we *know* that the 3.2 and 3.3 distribution are 
compiled with different compilers and run with different C runtimes, it 
is possible that some of the difference is from that and not from python 
at all.


tjr



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


Re: Python install Win 7 Problem

2013-04-03 Thread Terry Jan Reedy

On 4/3/2013 1:51 PM, Martin Schöön wrote:

On 2013-04-02, balasubramanian Achuthan balasu...@gmail.com wrote:

Try using Activestate python. The free version would suffice your
needs and it comes with a clean install.


I have been travelling and have not had time to read this thread in
detail so this may be old hat but on Windows (at work) I simply
install Python(x,y)

https://code.google.com/p/pythonxy/


Only available for 2.x



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


Re: IDLE printing problem

2013-04-03 Thread Terry Jan Reedy

On 4/3/2013 12:24 PM, Joe Hill wrote:
On 4/3/2013 12:24 PM, Joe Hill wrote:
 I attempted to print about 10 pages of documentation from the help files
 using IDLE.  On all the pages the side of each page was missing about 1/4
 inch of text.

You neglected to say what you actually did to have a problem. I tried 
the following with the font set to the default Courier.

 help(tuple)
a page and a half of help text
print to Canon inkjet or HP Laserjet 5
Everything printed, with longest lines just fitting within the margins.

 Am I missing a setting?  Is this a known problem?  Will it do the same
 with lines of code?

Printing depends on font, font size, OS printer driver, and printer. I 
suspect Idle just sends print command to tk text widget. Its 'print 
dialog' is as primitive as possible: the only choice is to print to the 
default printer or not; no printer choice, no page setup. Tk, in turn, 
should just put the text in a temporary file and turn it over to the OS 
printer driver.


 Using W7, 64 bit. PY 3.3.

 It worked just fine when I pasted the text in Word 2010.

I am sure it is has more knowledge about the vagaries of printing. You 
might try a single page (with max length lines) after Word prints to see 
if it left the printer in a better state.




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


Re: IDLE printing problem

2013-04-03 Thread Terry Jan Reedy

On 4/3/2013 2:50 PM, Joe Hill wrote:

On Wed, 03 Apr 2013 14:40:38 -0400, Terry Jan Reedy tjre...@udel.edu
wrote:




On 4/3/2013 12:24 PM, Joe Hill wrote:

I attempted to print about 10 pages of documentation from the help files
using IDLE.  On all the pages the side of each page was missing about 1/4
inch of text.


You neglected to say what you actually did to have a problem.



Text that I needed to make sense of the page did not print from the help
file.  Characters were missing on the right side on every long line on
every page.


I got that already. Until you say what you did, in enough detail to 
reproduce your actions, I cannot comment further.



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


Re: Time zone changing while Win app is running

2013-04-03 Thread Terry Jan Reedy

On 4/3/2013 2:46 PM, CM wrote:

On Apr 3, 7:37 am, Steven D'Aprano steve
+comp.lang.pyt...@pearwood.info wrote:

On Tue, 02 Apr 2013 17:04:12 -0700, CM wrote:

To summarize the issue:  In an application, I have been using Python's
datetime module to get the current time.  But it seems that, at least
with Windows (XP), whatever time zone your computer is set to when you
start the application, that's what datetime will use--the time zone will
*not* be updated in the application when you update it manually with
Windows.  So, if you change the time zone (say, after traveling with
your laptop), all datetimes will be incorrect as compared to your system
clock.


I am not the maintainer of the datetime module, but based purely on what
you have said, I would consider that a bug.


I don't. Do you really want every time function slowed by 
re-initializing the timezone?



I suggest you report it as an issue on the Python bug tracker.


I do believe that time.tzget can now be make to work now on Windows, and 
that would be a proper tracker issue.


Thanks, I submitted an issue about it.  On 2.7.3, on Windows, it's
easy to demonstrate:

(Actual time = 2:40pm; tz = Eastern U.S.)


import datetime
print datetime.datetime.now()

2013-04-03 14:40:03.124000  RIGHT

(Now change time zone to UTC, for example.  Now clock reads 6:41pm.)



import datetime


Without a restart, this is a no=op.


print datetime.datetime.now()

2013-04-03 14:41:13.124000  WRONG


As I said on the issue, passing a tz arg to now() will give the answer 
for any timezone on earth. A user-friendly app displaying times should 
let users choose.


--
Terry Jan Reedy


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


Re: IDLE printing problem

2013-04-03 Thread Terry Jan Reedy

On 4/3/2013 5:16 PM, Joe Hill wrote:

On Wed, 03 Apr 2013 16:20:20 -0400, Terry Jan Reedy tjre...@udel.edu
wrote:


On 4/3/2013 2:50 PM, Joe Hill wrote:

On Wed, 03 Apr 2013 14:40:38 -0400, Terry Jan Reedy tjre...@udel.edu
wrote:




On 4/3/2013 12:24 PM, Joe Hill wrote:

I attempted to print about 10 pages of documentation from the help files
using IDLE.  On all the pages the side of each page was missing about 1/4
inch of text.


You neglected to say what you actually did to have a problem.



Text that I needed to make sense of the page did not print from the help
file.  Characters were missing on the right side on every long line on
every page.


I got that already. Until you say what you did, in enough detail to
reproduce your actions, I cannot comment further.




I Open IDLE and click on Help and select the second option which is
Documentation - select Glossary.


The three options I see are
1) 'About Idle',
2) 'Idle help', which brings as a 2 page doc starting [See the end of 
this file for ** TIPS **, and
3) Python Docs - F1. On Windows, this third option brings up Windows 
Help opened to the windows-help version of the docs, which are also 
available online in a browser. In either case, Glossary is one of the docs.


We have left IDLE so your problem has nothing to do with IDLE. On 
Windows, one can open the same doc from the Start menu by selecting 
Python x.y / Python Docs.



I then click on the Print icon at the
top of the Help/Documentation screen - then let er rip.
The word/line wrap on the screen is ok and the printed output is not.


The word wrap on the screen adjusts to the window width. With the window 
too wide for the printer, I selected about five paragraphs, printed the 
selection, and the text was properly re-wrapped for printing with 
nothing lost, as if the display window had been narrowed. Windows 
obvious knows how wide the virtual window is for the particular 
combination of font (about 14 pt proportional sans serif) and printer. 
Apparently it is mis-calculating for your font and printer combination.



This was all unexpected outcomes.
I appreciate your help and that perhaps a fix can be found for everyone.
Mine is a very standard setup W7 Ult, 64bit  and an Epson printer
(WP-4020)


I have 64 bit Win7 pro with Canon and HP printers. The help window with 
a sheet+? icon in the upper left is Microsoft's program. The only thing 
I can suggest is to check for updated drivers, and make sure you have 
the correct driver.


--
Terry Jan Reedy


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


Windows printing problem (was re; IDLE printing problem_

2013-04-03 Thread Terry Jan Reedy

On 4/3/2013 6:26 PM, Joe Hill wrote:


In light of the fact that this is a new problem and has only occurred in
Python - I shall just regard that as either a feature or flaw...


Based on what you have said, the problem IS NOT OCCURRING IN PYTHON.
It is occurring in the Microsoft HTML help viewer.


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


Re: Data storage Py 3.3

2013-04-03 Thread Terry Jan Reedy

On 4/3/2013 6:53 PM, Irmen de Jong wrote:

On 4-4-2013 0:33, Joe Hill wrote:

IDLE wants to use Python33 as the data storage folder - with exe files
etc.
Typically the 'default data storage' is in 'last used' directory or most
programs even have a browse setting that one can quickly set and reset.

What do people here generally do?

When I installed 3.3, (W7- 64) I selected the first option for paths etc.
and everything seems to just run fine


I have a c:\Programs folder where I put multiple versions of python and 
selected other programs whose directories I might want to visit.



Don't store your files in the Python33 directory even though it is idle's 
default
suggestion.


I once did that, but then I had to move stuff when the Python x.y 
directory became obsolete. It was also a problem when I wanted to test a 
file with more than one python version.


I have my Python code sitting in appropriate subdirectories of a 'Projects' 
folder
somewhere (on a different drive on my Windows system, or just a subfolder in my
homedirectory on my Linux VM).


I have a file tem.py in my miscellaneous python directory. When I am 
writing possibly throwaway code, I open it from the recent files list, 
empty the old code, and go. I can always save as another name if I want 
to keep the code. tem.py is almost always on the list because I use it 
frequently.



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


Re: Fwd: Python subdomains https

2013-04-02 Thread Terry Jan Reedy

On 4/2/2013 7:05 AM, Jakub Muszynski wrote:

Hi,

I need to add python.org http://python.org https to my company
firewall policy, but I'm not allowed to add rule for
https://*.python.org http://python.org subdomains.

Can You give me/publish list of important subdomains (like
https://pypi.python.org) so I won't miss important sites?


docs - for the online docs
bugs - for the issue tracker
hg   - for the source repository
svn  - for the external dependencies for building python

You could also try all the links on python.org to see if there is 
anything else. psf.python.org? or is it only python.org/psf?


Python.org is getting a facelift under a paid contract, so things might 
change in the future. I believe the trend is toward more sugdomains.


--Terry



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


  1   2   >