Fraud

2016-04-16 Thread Mel Drosis via Python-list

My phone my accounts my home network have all been affected because of someone 
using coding from Python and Linux and GitHub and json. I don't even know what 
this stuff is but how do I get rid of it all. It's ruined my life. 
Sent from my iPhone
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: anomaly

2015-05-11 Thread Mel Wilson
On Sun, 10 May 2015 14:12:44 -0500, boB Stepp wrote:

 I have to admit being surprised by this, too. I am just now studying on
 how to write my own classes in Python, and have come to realize that
 doing this is *possible*, but the *surprise* to me is why the language
 design allowed this to actually be done.

Read Cory Doctorow lately on the War Against General Purpose Computing, 
where a bunch of people who don't really understand are trying to make it 
impossible for any computer to do something that is The Wrong Thing.  Or 
gently approach the relevant computing theory through Doug Hofstadter's 
_Goedel, Escher, Bach_, or some essays in _Metamagical Themas_.  
Generally speaking, making a computer totally incapable of doing Wrong 
Things leaves it incapable of doing anything at all.

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


Re: anomaly

2015-05-11 Thread Mel Wilson
On Tue, 12 May 2015 02:35:23 +1000, Steven D'Aprano wrote:

 On Mon, 11 May 2015 11:37 pm, Mel Wilson wrote:
 
 On Sun, 10 May 2015 14:12:44 -0500, boB Stepp wrote:
 
 I have to admit being surprised by this, too. I am just now studying
 on how to write my own classes in Python, and have come to realize
 that doing this is *possible*, but the *surprise* to me is why the
 language design allowed this to actually be done.
 
 Read Cory Doctorow lately on the War Against General Purpose Computing,
 where a bunch of people who don't really understand are trying to make
 it impossible for any computer to do something that is The Wrong Thing.
 
 I think you are conflating two different ideas of the Wrong Thing.

I don't think so.  A formal solution to a problem, i.e. a solution coded 
as a computer program, is limited to the things that can be done using 
formal techniques.  Whether it's people trying to enact their social 
standards in code, or whether it's people trying to nail the door shut 
against everything they don't expect, or think is illogical, the 
limits will still be there.

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


Re: Instead of deciding between Python or Lisp for a programming intro course...What about an intro course that uses *BOTH*? Good idea?

2015-05-10 Thread Mel Wilson
On Sun, 10 May 2015 13:43:03 -0700, Chris Seberino wrote:

 Instead of learning only Scheme or only Python for a one semester intro
 course, what about learning BOTH?  Maybe that could somehow get the
 benefits of both?
 
 I'm thinking that for the VERY beginning, Scheme is the fastest language
 to get beginners up and running writing code due to the extremely
 minimal simple syntax.
 
 I'm thinking half way into the semester, instead of moving into
 intermediate Scheme, perhaps that is a good time to switch to Python?
 
 Would a little strong intro to 2 nice languages in one semester be
 same/good/worse/better than just 1?

The first course I took, we learned Algol-60, then when we couldn't get 
computer time for compiles, we were asked to pick up FORTRAN-IV on the 
side.  So we published our solutions to the class problems in Algol and 
re-wrote them to be run in FORTRAN.  It was a fine first-hand look at 
what the general purpose in General Purpose Computer really meant.  
There was no confusing the machine and the language after that.  Scheme/
Python would be even more radical, I think.  If you can put them across 
effectively, I say go for it.

Mel.
 
 cs

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


Re: How to properly apply OOP in the bouncing ball code

2015-05-08 Thread Mel Wilson
On Fri, 08 May 2015 08:40:34 -0700, Tommy C wrote:

 I'm trying to apply OOP in this bouncing ball code in order to have
 multiple balls bouncing around the screen. The objective of this code is
 to create a method called settings, which controls all the settings for
 the screen and the bouncing behaviour of multiple balls, under the class
 Ball. However, I keep on getting errors related to attributes (e.g.,
 speed). I'm new to OOP in Python so your help will be much appreciated.
 Thanks in advance.

I did something similar, with little characters running around the screen 
under joystick control.  What I think:

1. Each instance of the Ball class should control the behaviour of one 
ball.
2. The screen settings and global environment generally should be global, 
not stuffed inside the behaviour of a Ball.
3. Keeping the list of Ball instances should be something the main 
section of your program does, not stuffed inside the behaviour of a Ball.

Each of my little GamePlayer objects is subclassed from 
pygame.sprite.Sprite .  I forget what I got by doing this (it's old code) 
but looking up the docs for that class might give you some insights.  
Each GamePlayer object has an update method which accepts info from the 
joystick and updates the player's movements, and a draw method which 
the main loop calls on displaying every frame, to show the player's new 
position and attitude.

You might be able to do something along these lines.

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


Re: functions, optional parameters

2015-05-08 Thread Mel Wilson
On Sat, 09 May 2015 03:49:36 +1000, Chris Angelico wrote:

 Yes, but can you *distinguish* them in terms of default argument versus
 code object creation? How do you know that the function's code object
 was created when compile() happened, rather than being created when the
 function was defined? Is there anything that lets you in any way show
 different behaviour based on that timing difference?

This might show that default objects are fixed at run time:

Python 2.7.3 (default, Mar 14 2014, 11:57:14) 
[GCC 4.7.2] on linux2
Type help, copyright, credits or license for more information.
 a = []
 def b (arr=a):
...   arr.append ('c')
... 
 print repr(a)
[]
 b()
 print repr(a)
['c']
 b()
 print repr(a)
['c', 'c']
 

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


Re: New to Python - block grouping (spaces)

2015-04-19 Thread Mel Wilson
On Sun, 19 Apr 2015 09:03:23 -0700, Rustom Mody wrote:

 Now if Thomson and Ritchie (yeah thems the guys) could do it in 1970,
 why cant we revamp this 45-year old archaic program=textfile system
 today?

Dunno.  Why not?  There's half of you right there.

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


Re: New to Python - block grouping (spaces)

2015-04-19 Thread Mel Wilson
On Mon, 20 Apr 2015 03:53:08 +1000, Steven D'Aprano wrote:

 On Mon, 20 Apr 2015 02:03 am, Rustom Mody wrote:

 Well evidently some people did but fortunately their managers did not
 interfere.
 
 You are assuming they had managers. University life isn't exactly the
 same as corporate culture.

IIRC Thompson, Ritchie, et al. were working at Bell Labs.  Legend has it 
that management would not buy them a Multics, so they were forced to 
write their own using the hardware they had.

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


Re: Best search algorithm to find condition within a range

2015-04-08 Thread Mel Wilson
On Wed, 08 Apr 2015 07:56:05 -0700, jonas.thornvall wrote:

 There is no need for inventing a new set of characters representing
 32-bit numbers. You will not be able to learn them by heart anyway,
 unless they build on a interpretation system binaries, decimals.

See Jorge Luis Borges, _Funes the Memorious_.  Gotta keep up with the 
literature.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Best search algorithm to find condition within a range

2015-04-08 Thread Mel Wilson
On Tue, 07 Apr 2015 23:19:49 -0700, jonas.thornvall wrote:

 And you have just created 429496729 unique symbols ;), in a pencil
 stroke.

No.  You did that, when you said base 429496729.  Representing the 
symbols in a computer is no problem, any Python long int can do that.  To 
display the symbols, you can use PIL to make up glyphs out of coloured 
pixels 864x864.  You can keep your glyphs in GIFs.  Where you keep them 
is up to you.  Keeping them in Tumbolia and computing them out as 
required will work well.

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


Re: Programming D. E. Knuth in Python with the Deterministic Finite Automaton construct

2012-03-17 Thread Mel Wilson
Antti J Ylikoski wrote:

 
 In his legendary book series The Art of Computer Programming,
 Professor Donald E. Knuth presents many of his algorithms in the form
 that they have been divided in several individual phases, with
 instructions to GOTO to another phase interspersed in the text of the
 individual phases.
 
 
 
 I. e. they look like the following, purely invented, example:  (Knuth is
 being clearer than me below.)
 
 
 
 A1.  (Do the work of Phase A1.)  If zap then go to Phase A5,
 otherwise continue.
 
 A2.  (Do some work.) If zorp go to Phase A4.
 
 A3.  (Some more work.)
 
 A4.  (Do something.)  If condition ZZZ go to Phase A1.
 
 A5.  (Something more).  If foobar then go to Phase A2, otherwise
 end.
 
 
 
 I came across the problem, which would be the clearest way to program
 such algorithms with a programming language such as Python, which has
 no GOTO statement.  It struck me that the above construction actually
 is a modified Deterministic Finite Automaton with states A1 -- A5 +
 [END], transferring to different states, not on read input, but
 according to conditions in the running program.
 
 So one very clear way to program Knuth with Python is the following
 kind of a construct.

Yeah.  This is an idea that came up during the '70s after Dijkstra published 
his GOTO Considered Harmful.  Model the execution pointer as a state, and 
then explicit changes to the execution pointer (prohibited in GOTO-less 
languages) get replaced by assignments to the state.  It preserves the 
objectionable part of GOTO: that there's no easy way to predict the 
conditions that any statement might execute under.  You can't understand any 
of the program until you understand all of the program.

I think Knuth kept the assembly-language model for his algorithms because it 
promotes his real goal, which is mathematical analysis of the performance of 
the algorithms.  It helps that his algorithms are very short.

As the quickest way to get a Knuth algorithm running in Python, this is a 
pretty good idea.  My own preference is to get the algo really coded in 
Python, but that usually takes a fair bit of time and effort.

Mel.

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


[issue14353] Proper gettext support in locale module

2012-03-17 Thread Mel Flynn

Mel Flynn rfl...@acsalaska.net added the comment:

Additional patch for 2.7 branch.

--
Added file: http://bugs.python.org/file24918/python27-configure.in.patch

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue14353
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue14353] Proper gettext support in locale module

2012-03-17 Thread Mel Flynn

New submission from Mel Flynn rfl...@acsalaska.net:

Gettext support in Python is configured by two tests:
- textdomain in libc or libintl
- bind_textdomain_codeset in libc only

The latter causes incomplete gettext support in the locale module. Since the 
implementation uses two different defines, the provided patch provides them and 
also ensures they exist.

The issue is not present in 3.x branches, as only a single test is done for 
full gettext support in locale.

--
components: Build
files: python26-configure.in.patch
keywords: patch
messages: 156203
nosy: melflynn
priority: normal
severity: normal
status: open
title: Proper gettext support in locale module
type: enhancement
versions: Python 2.6, Python 2.7
Added file: http://bugs.python.org/file24917/python26-configure.in.patch

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue14353
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Re: Python is readable

2012-03-16 Thread Mel Wilson
Steven D'Aprano wrote:

 On Fri, 16 Mar 2012 17:53:24 +, Neil Cerutti wrote:
 
 On 2012-03-16, Steven D'Aprano steve+comp.lang.pyt...@pearwood.info
 wrote:
 Ah, perhaps you're talking about *prescriptivist* grammarians, who
 insist on applying grammatical rules that exist only in their own
 fevered imagination. Sorry, I was talking about the other sort, the
 ones who apply the grammatical rules used by people in real life. You
 know the ones: linguists. My mistake.
 
 I am not pedantic. You are wrong.
 
 
 Whether you like it or not, it simply is a fact that in English (I won't
 speak for other languages) people use colons without the first clause
 *necessarily* being a complete sentence. They write things like this:
 
 Star Wars Episode IV: A New Hope

Come to think of it, just about every serious book title works this way.

Mel.

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


Re: A 'Python like' language

2012-03-03 Thread Mel Wilson
Paul Rubin wrote:

 dreamingforw...@gmail.com writes:
 hanging out on the Prothon list now and then, at least until we get
 the core language sorted out?

 Haha, a little late, but consider this a restart.
 
 It wasn't til I saw the word Prothon that I scrolled back and saw you
 were responding to a thread from 2004.  Prothon was pretty cool in some
 ways but I think it's been inactive for a very long time.  I don't see
 much point to developing a slightly improved but incompatible
 Python-like language anyway though.  Why make superficial changes that
 break working code and mentally overload programmers?  Python is a
 relatively mature language by now, so it shouldn't be messed with unless
 the changes produce drastic benefits, not minor ones.

A website still exists, but I don't see signs of a new language; looks like 
a watering hole for some techies.

Prothon looked interesting as long as it promised to be about Python that 
used prototypes instead of classes to organize objects.  What happened, 
though, was that it turned into a crusade to remove every Python wart that a 
bunch of people could imagine.  The band of developers might have had the 
steam for the new object model, but they didn't have the steam to do 
everything.

Mel.

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


Re: Is it necessary to call Tk() when writing a GUI app with Tkinter?

2012-03-02 Thread Mel Wilson
Terry Reedy wrote:

 The problem was another subtle bug in the current example:
  self.hi_there[text] = Hello,
 
 The spurious comma at the end makes the value of the 'text' attribute a
 one-elememt tuple and not just a string. I presume tcl-based tk handles
 that in the manner appropriate for the tcl equivalent. I believe tcl
 uses spaces rather than commas to separate items, so the braces serve as
 'quotes' to indicate that the contents are one item, not three. Removing
 the comma solves the problem.

That looks like it.  Tcl is the 'LISP of strings'  Composite-object things 
like indexing work on space-separated strings.


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


Re: PyWart: Language missing maximum constant of numeric types!

2012-02-24 Thread Mel Wilson
Rick Johnson wrote:

 I get sick and tired of doing this!!!
 
 if maxlength == UNLIMITED:
 allow_passage()
 elif len(string)  maxlength:
 deny_passage()
 
 What Python needs is some constant that can be compared to ANY numeric
 type and that constant will ALWAYS be larger!

Easily fixed:



class Greatest (object):
def __cmp__ (self, other):
if isinstance (other, Greatest):
return 0
return 1

def __hash__ (self):
return id (Greatest)

class Least (object):
def __cmp__ (self, other):
if isinstance (other, Least):
return 0
return -1

def __hash__ (self):
return id (Least)



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


Re: atexit.register in case of errors

2012-02-15 Thread Mel Wilson
Andrea Crotti wrote:

 I have the following very simplified situation
 
 from atexit import register
 
 
 def goodbye():
  print(saying goodbye)
 
 
 def main():
  while True:
  var = raw_input(read something)
 
 
 if __name__ == '__main__':
  register(goodbye)
  main()
 
 
 But in my case the goodbye function is deleting the logging file which
 was created
 during the application execution.
 Now the problem is that it *always* executes, even when the applications
 quits for
 some bad errors.
 
 Is there a way to have an exit hook, which doesn't execute in case of
 errors?
 I've seen the code of atexit and it apparently doesn't know anything
 about the current
 status and why the application is actually quitting, is that correct?

That's sort of the point: to do things that simply *have* to happen, even if 
you've lost control of the program.

The usual way to do what you're asking is

if __name__ == '__main__':
main()
goodbye()

and write main so that it returns after it's done all the things it's 
supposed to do.  If you've sprinkled `sys.exit()` all over your code, then 
don't do that.  If you're forced to deal with a library that hides 
`sys.exit()` calls in the functions, then you have my sympathy.  Library 
authors should not do that, and there have been threads on c.l.p explaining 
why they shouldn't.

Mel.

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


Re: name of a sorting algorithm

2012-02-14 Thread Mel Wilson
Jabba Laci wrote:
 Could someone please tell me what the following sorting algorithm is
 called?
 
 Let an array contain the elements a_1, a_2, ..., a_N. Then:
 
for i in xrange (N-1):
for j in xrange (i, N):
if a[j]  a[i]:
a[i], a[j] = a[j], a[i]
 
 It's so simple that it's not mentioned anywhere. I guess it's called
 selection sort but I'm not sure. The minimum selection sort is an
 improvement of this one.

It's what Wikipedia says a selection sort is: put the least element in [0], 
the least of the remaining elements in [1], etc.

Mel.

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


RE: name of a sorting algorithm

2012-02-14 Thread Mel Wilson
Prasad, Ramit wrote:

 
 for i in xrange (N-1):
 for j in xrange (i, N):
 if a[j]  a[i]:
 a[i], a[j] = a[j], a[i]
 It's what Wikipedia says a selection sort is: put the least element in
 [0], the least of the remaining elements in [1], etc.
 
 If your only requirement to match to selection sort is the end result,
 then every sort would be selection sort. If you meant put the least
 element in [0] in the first pass then that would indeed be selection
 sort, but that is not what the above code does. The above code is bubble
 sort.

Well, the classic bubble sort swaps adjacent elements until the extreme one 
gets all the way to the end.  This sort continually swaps with the end 
element during one pass until the end element holds the extreme.  Then it 
shrinks the range and swaps then next less extreme into the new end element.  
It does extra swaps because it combines the swap operation with recording 
the temporary extreme while it searches the subrange.

Mel.

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


Re: name of a sorting algorithm

2012-02-14 Thread Mel Wilson
Den wrote:

 I disagree.  In a bubble sort, one pointer points to the top element,
 while another descents through all the other elements, swapping the
 elements at the pointers when necessary.

'When I use a word,' Humpty Dumpty said, in rather a scornful tone, 'it 
means just what I choose it to mean — neither more nor less.' (_Through the 
Looking Glass, Lewis Caroll).  And you, too, have that ability.  
Contrariwise see Knuth, _The Art of Computer Programming_ Section 5.2.2, 
Algorithm B.

Mel.


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


Re: M2crypto

2012-02-12 Thread Mel Wilson
zigi wrote:

 Hello,
 M2crypto
 
 __init__(self, alg, key, iv, op, key_as_bytes=0, d='md5',
 salt='12345678', i=1, padding=1)
 
 I wont write app, using M2crypto and I can not understand what are the
 arguments:
 key, iv, op, salt ?
 What they do ?

I assume you're reading in http://www.heikkitoivonen.net/m2crypto/api/ 
about M2Crypto.EVP.Cipher.

Epydoc claims another victim.

I'm having a lot of trouble finding documentation.  The obvious OpenSSL 
pages are kind of thin, too.  You might see some useful code in the EVP unit 
tests m2crypto/tests/test_evp.py in the m2crypto installation.

Good hunting,   Mel.

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


Re: difference between random module in python 2.6 and 3.2?

2012-02-06 Thread Mel Wilson
Steven D'Aprano wrote:

 A more explicit note will help, but the basic problem applies: how do you
 write deterministic tests given that the random.methods (apart from
 random.random itself) can be changed without warning?

Biting the bullet would mean supplying your own PRNG, under your control.  
Jon Bentley somewhere, sometime, published a portable PRNG for that exact 
reason.  (I wish I could find that article.)  Specifically he wanted 
portability across various manufacturer's O/Ss.

Mel.

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


Re: python reliability with EINTR handling in general modules

2012-02-02 Thread Mel Wilson
Dennis Lee Bieber wrote:

 On Wed, 1 Feb 2012 23:25:36 -0800 (PST), oleg korenevich
 void.of.t...@gmail.com wrote:
 
 
Thanks for help. In first case all vars is python integers, maybe
math.floor is redundant, but i'm afraid that same error with math
module call will occur in other places of app, where math is needed.
Strange thing here is that math library call is not a system call, and
strange exception ValueError (all values have right values) and why in
braces i have (4, Interruted system call).

 math.floor() may still be a system call of some sort if access to
 the math processor requires synchronization between processes (that is,
 the math processor/registers are maintained as a separate structure
 apart from the task status during process switches). {Yes -- that is a
 wild hypothesis}

One thing to remember about errno is that C library code will set it to a 
non-zero value when an error is encountered, but (I believe) there's no 
requirement to clear it in the absence of an error.  EINTR might just be 
left over from some long-gone I/O call, then reported just in case in 
handling an exception that didn't involve the C library at all.

As a C coder there are times when it's wise to clear errno yourself to make 
sure your code doesn't get fooled.

Mel.

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


Re: Question about name scope

2012-02-01 Thread Mel Wilson
Dave Angel wrote:

 I tried your experiment using Python 2.7 and Linux 11.04
 
 
 def f(a):
  from math import sin, cos
  return sin(a) + cos(a)
 
 print f(45)
 
 Does what you needed, and neatly.  The only name added to the global
 namspace is f, of type function.
 
 I was a bit surprised that using   from math import * inside the
 function worked, but it generates  a warning:
 olive.py:2: SyntaxWarning: import * only allowed at module level
def f(a):

I guess they want local symbols in functions to be pre-compiled.  Similar to 
the way you can't usefully update the dict returned by locals().  Strangely, 
I notice that

Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) 
[GCC 4.4.3] on linux2
Type help, copyright, credits or license for more information.
 def f(x):
...   exec x
...   exec 'print a'
... 
 f('a=4')
4
 

works, but I really cannot explain why.

Mel.

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


Re: except clause syntax question

2012-01-31 Thread Mel Wilson
Charles Yeomans wrote:

 To catch more than one exception type in an except block, one writes
 
 except (A, B, C) as e:
 
 I'm wondering why it was decided to match tuples, but not lists:
 
 except [A, B, C] as e:
 
 The latter makes more sense semantically to me -- catch all exception
 types in a list as opposed to catch this single thing composed of three
 exception types.

On reflection, it seems to hint at a style that Python extensions were made 
in.  (IIRC) the first operand in an `except` statement was originally just 
an arbitrary marker to identify the exception.  Unique string values were 
customary, although the Python library defined things with standard 
exception names.  Using a string means that general exceptions weren't to be 
collected in general sequences; `except Serious Error` was never meant to 
catch `raise r`.  If only tuples were used for collections, it would 
create havoc for fewer of any weirdos who had used strange markers of their 
own devising.

It looks like tuples were chosen as the most lightweight, or maybe least 
intrusive, sequence type to require to denote a collection of exceptions.

You see a similar decision, with the opposite emphasis, with the string 
modulo operator.  The second operand is supposed to be a tuple, but if the 
template string needs only one value, then the rules are relaxed and any 
single non-tuple value is used as-is.


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


Re: except clause syntax question

2012-01-31 Thread Mel Wilson
Chris Angelico wrote:

 On Wed, Feb 1, 2012 at 9:03 AM, Duncan Booth
 duncan.booth@invalid.invalid wrote:
 Abitrarily nested tuples of exceptions cannot contain loops so the code
 simply needs to walk through the tuples until it finds a match.
 
 Is this absolutely guaranteed? The C API for CPython provides:
 (Py2) http://docs.python.org/c-api/tuple.html#PyTuple_SetItem
 (Py3) http://docs.python.org/dev/c-api/tuple.html#PyTuple_SetItem
 
 which doesn't have massive warnings on it saying USE THIS ONLY TO
 INITIALIZE A TUPLE (compare, for instance, _PyTuple_Resize which does
 carry a similar warning). Is the assumption then that we're all
 adults, and that mutating a tuple is like passing a null pointer to an
 API function (aka loaded gun in proximity to foot)?

Unfortunately, I can't remember the details now, but I once set out to 
create a recursive tuple by using the C API, and it turned out then that the 
C API went to some lengths to prevent anyone being able to do that.  I did 
finally do it in some peculiar way, but it wasn't simple.  The c.l.python 
archives might still have the post where I described it.

Mel.

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


Re: except clause syntax question

2012-01-30 Thread Mel Wilson
Charles Yeomans wrote:

 To catch more than one exception type in an except block, one writes
 
 except (A, B, C) as e:
 
 I'm wondering why it was decided to match tuples, but not lists:
 
 except [A, B, C] as e:
 
 The latter makes more sense semantically to me -- catch all exception
 types in a list as opposed to catch this single thing composed of three
 exception types.

I've always been perfectly fine with sometimes treating tuples as immutable 
sequences, so I'm +0 on saying more sense semantically, but given that the 
exception list can be a variable, I'm not sure what the gain is by keeping 
it immutable.

#---
#!/usr/bin/env python
# -*- coding: ASCII -*-
'''Demonstrate catching variable exceptions.
'''
def excepter (a, exceptions):
try:
1.0/a
'Number ' + a
except exceptions as e:
print '!!! *** EXCEPTER CAUGHT ONE *** !!!'
print repr (e)

#~ excepter (0, [ZeroDivisionError])
excepter (0, (ZeroDivisionError,))
excepter (1, (ZeroDivisionError,TypeError))
excepter (1, (ZeroDivisionError,))

 #---

excepter called with the list catches nothing, of course.


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


Re: verify the return value of a function

2012-01-20 Thread Mel Wilson
Jean-Michel Pichavant wrote:

 isinstance is fine, if you could find the source where it is
 discouraged... Could be a consequence of some specific context.
 However, checking types in OOP is in general a failure. Unitary tests
 are possibly an exception.

I think it's discouraged when people try to write big overloaded functions 
that check the types of the arguments to decide what they should be doing.
In diagnostics and tests like the OP's there should be no problem.

Mel.

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


Re: mutually exclusive arguments to a constructor

2011-12-30 Thread Mel Wilson
Adam Funk wrote:

 (Warning: this question obviously reflects the fact that I am more
 accustomed to using Java than Python.)
 
 Suppose I'm creating a class that represents a bearing or azimuth,
 created either from a string of traditional bearing notation
 (N24d30mE) or from a number indicating the angle in degrees as
 usually measured in trigonometry (65.5, measured counter-clockwise
 from the x-axis).  The class will have methods to return the same
 bearing in various formats.
 
 In Java, I would write two constructors, one taking a single String
 argument and one taking a single Double argument.  But in Python, a
 class can have only one __init__ method, although it can have a lot of
 optional arguments with default values.  What's the correct way to
 deal with a situation like the one I've outlined above?

Cleanest from the point of view of the class source code would be factory 
functions at the module level, or special classmethods to deal with the less 
common cases.  You see this a lot in wxPython when they have to deal with 
overloaded C++ constructors.

Most like the Java would be to check within __init__ for a string argument 
that could be parsed as a bearing, and failing that fall back to treating 
the argument as a numeric angle.

Neither fish nor fowl would be to accept named arguments for the different 
kinds of values.

Mel.

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


Re: Early and late binding [was Re: what does 'a=b=c=[]' do]

2011-12-23 Thread Mel Wilson
Steven D'Aprano wrote:
 On Fri, 23 Dec 2011 13:13:38 +, Neil Cerutti wrote:
 On 2011-12-23, Neil Cerutti ne...@norwich.edu wrote:
 ...you know, assuming it wouldn't break existing code. ;)
 
 It will. Python's default argument strategy has been in use for 20 years.
 Some code will rely on it. I know mine does.

In a tool that's meant for other people to use to accomplish work of their 
own, breaking workflow is a cardinal sin.

In a research language that's meant always to be up-to-date with the concept 
of the week, not so much.

Mel.

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


Re: Pythonification of the asterisk-based collection packing/unpacking syntax

2011-12-22 Thread Mel Wilson
Chris Angelico wrote:

 On Fri, Dec 23, 2011 at 1:13 AM, Hans Mulder han...@xs4all.nl wrote:
 How about:

 class name=MyClass superclasses=A, B, C
 ...
 /class

 More more readable!  And it's a standard!
 
 Unfortunately it's not Pythonic, because indentation is insignificant.

Easy-peasy:

 def name=method arguments=self, x, y
 indent/indentlet target=t

Mel.

 We need to adopt a more appropriate form. Eliminate all the /spam
 tags and use indentation to mark the ends of elements.
 
 ChrisA
 PS. Brilliant, sir, brilliant! I take off my cap to you.

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


Re: Making the case for typed lists/iterators in python

2011-12-16 Thread Mel Wilson
Chris Angelico wrote:

 It's no more strange than the way some people omit the u from colour. :)

Bonum Petronio Arbiteri, bonum mihi.

Mel.

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


Re: correct usage of a generator?

2011-11-28 Thread Mel Wilson
Tim wrote:

 Hi, I need to generate a list of file names that increment, like 
this:
 fname1
 fname2
 fname3 and so on.
 
 I don't know how many I'll need until runtime so I figure a 
generator is
 called for.
 
 def fname_gen(stem):
 i = 0
 while True:
 i = i+1
 yield '%s%d' % (stem,i)
 
 blarg = fname_gen('blarg')
 boo = fname_gen('boo')
 
 n = 3
 for w in range(0,n):
 in_name = blarg.next()
 out_name = boo.next()
 
 
 This works, but is it the 'normal' way to accomplish the task when 
you
 don't know 'n' until run-time? thanks,

It's kind of overkill in the toy demo example, but if the main loop is 
a little more abstract, e.g.

for task in task_supplier():
in_name = blarg.next()
out_name = boo.next()
handle_task (task, in_name, out_name)

then it's obviously a good thing.

One quibble (that Peter Otten also suggested): if your business rules 
expect that files blarg25 and boo25 (for example) work together, then 
you'd be better off generating them together as a pair in a single 
generator call.  As it is, there's a chance of the blarg and boo 
generators getting out of step and supplying mismatched names.

Mel.

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


Re: Close as Many Files/External resourcs as possible in the face of exceptions

2011-11-21 Thread Mel Wilson
GZ wrote:
 Here is my situation. A parent object owns a list of files (or other
 objects with a close() method). The close() method can sometimes 
fail
 and raise an exception. When the parent object's close() method is
 called, it needs to close down as many files it owns as possible, 
even
 if the close() function of some files fail. I also want to re-raise 
at
 least one of the original exceptions so that the outer program can
 handle it.
[ ... ]
 
 It will re-raise the first exception and preserve the context and
 close as many other files as possible while ignoring any further
 exceptions.
 
 But this looks really awkward. And in the case that two files fail 
to
 close, I am not sure the best strategy is to ignore the second
 failure.

I imagine you could save any caught exception instances in a list and 
study them later.

Mel.

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


Re: Use and usefulness of the as syntax

2011-11-12 Thread Mel Wilson
candide wrote:

 First, could you confirm the following syntax
 
 import foo as f
 
 equivalent to
 
 import foo
 f = foo
 
 
 
 Now, I was wondering about the usefulness in everyday programming of 
the
 as syntax within an import statement. [ ... ]

It gives you an out in a case like

Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) 
[GCC 4.4.3] on linux2
Type help, copyright, credits or license for more information.
 os = 5  # number of 'o's
 import os as opsys
 os
5
 opsys
module 'os' from '/usr/lib/python2.6/os.pyc'

(This is an instance of what arnaud mentioned.)

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


Re: How to isolate a constant?

2011-10-25 Thread Mel
Dennis Lee Bieber wrote:

 Where's the line form to split those who'd prefer the first vs the
 second result in this sample G:
 
 unExpected = What about a string
 firstToLast = unExpected[:]
 repr(firstToLast)
 'What about a string'
 explicitList = list(unExpected)
 repr(explicitList)
 ['W', 'h', 'a', 't', ' ', 'a', 'b', 'o', 'u', 't', ' ', 'a', ' ', 's',
 't', 'r', 'i', 'n', 'g']
 

Well, as things stand, there's a way to get whichever result you need.  The 
`list` constructor builds a single list from a single iterable.  The list 
literal enclosed by `[`, `]` makes a list containing a bunch of items.

Strings being iterable introduces a wrinkle, but `list('abcde')` doesn't 
create `['abcde']` just as `list(1)` doesn't create `[1]`.

Mel.

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


RE: Problem with a wx notebook

2011-10-20 Thread Mel
Prasad, Ramit wrote:

 I've created a wx NoteBook in wich I set multiples panels in wich I
 set one or more sizers. But nothing displays in the notebook,
 everything is outside. I've been searching an answer for 2 days .
 Can you help me plz ? Here is my code(with only one panel, to sum up
 the code) :
 
 class StreamingActivationDialog(wx.Dialog):
 def __init__(self, *args, **kwds):
 # begin wxGlade: StreamingActivationDialog.__init__
 kwds[style] = wx.DEFAULT_DIALOG_STYLE
 wx.Dialog.__init__(self, *args, **kwds)
 self.bitmap_1_copy = wx.StaticBitmap(self, -1, wx.Bitmap(img\
 \logo.png, wx.BITMAP_TYPE_ANY))
 self.labelDnD = wx.StaticText(self, -1, Si vous avez déjà un
 fichier d'activation, faite le glisser dans cette fenetre)
 self.keyBitmap = wx.StaticBitmap(self, -1, wx.Bitmap(img\
 \key.bmp, wx.BITMAP_TYPE_ANY))
 self.conclude = wx.StaticText(self, -1, _(test),
 style=wx.ALIGN_CENTRE)
 
 ### Panel ###
 self.intro3_label = wx.StaticText(self, -1, Envoyez un mail à
 \nactivat...@monmail.com\ncontenant le code :,style=wx.ALIGN_CENTRE)
 self.activationCode_label= wx.StaticText(self, -1,
 123456789, style=wx.TE_READONLY)
 self.copy2_Button = wx.Button(self, -1, Copier dans le presse-
 papier)
 self.copy2_Button.Bind(wx.EVT_BUTTON, PanelMail.onCopy)
 ##
 
 self.note = wx.Notebook(self, wx.ID_ANY, style=wx.BK_LEFT,
 size=wx.Size(100, 341))
 self.page3 = wx.Panel(self.note)
 
 imagelist = wx.ImageList(94, 94)
 bitmap1 = wx.Bitmap(img\\a.bmp, wx.BITMAP_TYPE_BMP )
 imagelist.Add(bitmap1)
 self.note.AssignImageList(imagelist)
 
 self.__set_properties()
 self.__do_layout()
 # end wxGlade
 
 def __set_properties(self):
 # begin wxGlade: StreamingActivationDialog.__set_properties
 self.SetTitle(_(Activation de FlashProcess))
 self.SetBackgroundColour(wx.Colour(255, 255, 255))
 #self.linkProblem.SetForegroundColour(wx.Colour(0, 0, 0))
 # end wxGlade
 
 def __do_layout(self):
 # begin wxGlade: StreamingActivationDialog.__do_layout
 self.grid_sizer_1 = wx.FlexGridSizer(6, 1, 0, 0)
 self.grid_sizer_2 = wx.FlexGridSizer(1, 2, 0, 30)
 self.grid_sizer_1.Add(self.bitmap_1_copy, 0, wx.TOP|wx.BOTTOM|
 wx.EXPAND, 10)
 
 
 ### Page 3 ###
 sizer = wx.BoxSizer(wx.VERTICAL)
 sizer.Add(self.intro3_label, 0, wx.BOTTOM|wx.ALIGN_CENTER, 5)
 sizer.Add(self.activationCode_label, 0, wx.BOTTOM|
 wx.ALIGN_CENTER, 20)
 sizer.Add(self.copy2_Button, 0, wx.ALIGN_CENTER, 20)
 
 self.page3.SetSizer(sizer)
 sizer.Fit(self.page3)
 ##
 
 self.note.AddPage(self.page3, , False, 0)
[ ... ]

It looks a though all the controls that are meant for page3 have been 
created with the top-level dialog as their parent.  AFAIK this cannot be.
self.page3 is (correctly) a child window of self.note, but the controls to 
be shown inside have to be children of self.page3 .  Putting things into the 
sizers is not enough.

In my own code, I usually define a separate class descended from wx.Panel to 
create a page3 instance with its own sizers, then create one of those with a 
a wx.Notebook instance as a parent, and add it to the notebook:

def _new_capture_page (self):
new_trace = TraceWindow (self.tracebook)
self.tracebook.AddPage (new_trace, 'Capture %d' %  
(self.capture_serial,), select=True)
return new_trace


Hope this helps,

Mel.


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


Re: Usefulness of the not in operator

2011-10-08 Thread Mel
Steven D'Aprano wrote:

 candide wrote:
 
 So what is the usefulness of the not in operator ? Recall what Zen of
 Python tells
 
 There should be one-- and preferably only one --obvious way to do it.
 
 And not in is the obvious way to do it.
 
 
 If the key is not in the ignition, you won't be able to start the car.
 
 If not the key is in the ignition, you won't be able to start the car.
 
 
 Who like that second one speaks?

:)  
If the key is not in the ignition, you will be able to start the car, not.

Mel.

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


Re: Wrote a new library - Comments and suggestions please!

2011-09-27 Thread Mel
Steven D'Aprano wrote:
 I googled on SAS PROC FREQ and found this:
 
http://support.sas.com/documentation/cdl/en/procstat/63104/HTML/default/procstat_freq_sect006.htm
 
 All the words are in English, but I have no idea what the function does,
 how you would call it, and what it returns. Would it have been so hard to
 show a couple of examples?

Hmm.  Yeah.  Very much so.  That's the kind of documentation I call syntax 
happy.  It tells you how to create a well-formed PROC STAT without ever 
saying what would happen if you did, or why you might want that, whatever it 
was, to happen.  I see that kind of documentation way too often.  By 
comparison, even this https://www.ubersoft.net/comic/hd/2011/09/losing-
sight-big-picture might seem good.  At least they try.

Does things to the stuff.  By default, the most recent stuff is done things 
to.

Mel.

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


Re: Generating equally-spaced floats with least rounding error

2011-09-24 Thread Mel
Steven D'Aprano wrote:

 I'm trying to generate a sequence of equally-spaced numbers between a
 lower and upper limit. Given arbitrary limits, what is the best way to
 generate a list of equally spaced floats with the least rounding error for
 each point?
 
 For example, suppose I want to divide the range 0 to 2.1 into 7 equal
 intervals, then the end-points of each interval are:
 
 (0.0)---(0.3)---(0.6)---(0.9)---(1.2)---(1.5)---(1.8)---(2.1)
 
 and I'd like to return the values in the brackets. Using Decimal or
 Fraction is not an option, I must use floats. If the exact value isn't
 representable as a float, I'm okay with returning the nearest possible
 float.
 
 The width of each interval is:
 
 width = (2.1 - 0.0)/7
 
 The relevant points can be calculated in either of two methods:
 
 #1 add multiples of the width to the starting value, 0.
 
 #2 subtract multiples of width from the ending value, 2.1.
 
 (Repeated addition or subtraction should be avoided, as it increases the
 amount of rounding error.)
 
 Mathematically the two are equivalent, but due to rounding, they may not
 be. Here's a run using Python 3.2:
 
 [0.0 + i*width for i in range(8)]
 [0.0, 0.3, 0.6, 0.8999, 1.2, 1.5, 1.7998, 2.1]
 
 The 4th and 7th values have rounding errors, the rest are exact.
 
 
 [2.1 - (7-i)*width for i in range(8)]
 [0.0, 0.30027, 0.6001, 0.9001,
 1.2002, 1.5, 1.8, 2.1]
 
 The 2nd, 3rd, 4th and 5th values have rounding errors. Note that the 7th
 value is exact here, but not above.
 
 Is there a way to pick between methods #1 and #2 (or some combination of
 the two) without human intervention so as to minimise the rounding error?
 Or is there some other way to generate equally-spaced floats? My efforts
 at googling have not been helpful.

When I've done this with ints (usually in small embedded systems) I've 
always preferred

low_limit + (total_width * i) / intervals

since it does the rounding on the biggest numbers where proportional error 
will be least, and it's guaranteed to hit the low_limit and high_limit 
exactly (as exactly as they can be represented, anyway.)

Mel.

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


Re: Context manager with class methods

2011-09-22 Thread Mel
Gavin Panella wrote:

 Hi,
 
 On Python 2.6 and 3.1 the following code works fine:
 
 class Foo(object):
 
 @classmethod
 def __enter__(cls):
 print(__enter__)
 
 @classmethod
 def __exit__(cls, exc_type, exc_value, traceback):
 print(__exit__)
 
 with Foo: pass
 
 However, in 2.7 and 3.2 I get:
 
 Traceback (most recent call last):
   File stdin, line 1, in module
 AttributeError: __exit__
 
 Is this a regression or a deliberate change? Off the top of my head I
 can't think that this pattern is particularly useful, but it seems
 like something that ought to work.

This seems to work:



class MetaWith (type):
@classmethod
def __enter__(cls):
print(__enter__)

@classmethod
def __exit__(cls, exc_type, exc_value, traceback):
print(__exit__)

class With (object):
__metaclass__ = MetaWith

with With:
pass



Mel.

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


Re: Context manager with class methods

2011-09-22 Thread Mel
Mel wrote:
 This seems to work:
 
 
 
 class MetaWith (type):
 @classmethod
 def __enter__(cls):
 print(__enter__)
 
 @classmethod
 def __exit__(cls, exc_type, exc_value, traceback):
 print(__exit__)
 
 class With (object):
 __metaclass__ = MetaWith
 
 with With:
 pass

It seems to work equally well without the `@classmethod`s

Mel.

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


Re: Doctest failing

2011-09-10 Thread Mel
Tigerstyle wrote:

 Hi guys.
 
 I'm strugglin with some homework stuff and am hoping you can help me
 out here.
 
 This is the code:
 
 small_words = ('into', 'the', 'a', 'of', 'at', 'in', 'for', 'on')
 
 def book_title(title):
  Takes a string and returns a title-case string.
 All words EXCEPT for small words are made title case
 unless the string starts with a preposition, in which
 case the word is correctly capitalized.
  book_title('DIVE Into python')
 'Dive into Python'
  book_title('the great gatsby')
 'The Great Gatsby'
  book_title('the WORKS OF AleXANDer dumas')
 'The Works of Alexander Dumas'
 
 new_title = []
 title_split = title.strip().lower().split()
 for word in title_split:
 if title_split[0] in small_words:
 new_title.append(word.title())
 elif word in small_words:
 new_title.append(word.lower())
 else:
 new_title.append(word.title())
 return(' '.join(new_title))
 
 def _test():
 import doctest, refactory
 return doctest.testmod(refactory)
 if __name__ == __main__:
 _test()
 
 All tests are failing even though I am getting the correct output on
 the first two tests. And the last test still gives me Of instead of
 of
 
 Any help is appreciated.

I don't know about doctest -- I suspect it wants a structured docstring to 
specify the tests -- but this

if title_split[0] in small_words:
new_title.append(word.title())

can't be what you want.

Mel.

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


Re: Mastering Python... Best Resources?

2011-08-26 Thread Mel
Chris Angelico wrote:
[ ... ]
 You can get books on algorithms from all sorts of places, and with a
 very few exceptions, everything you learn with apply to Python and
 also to every other language you use.

I liked _Programming Pearls_ by Jon Bentley.  No reference to Python -- that 
would be the O.P.'s job.

Mel.

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


Re: is there any principle when writing python function

2011-08-23 Thread Mel
smith jack wrote:

 i have heard that function invocation in python is expensive, but make
 lots of functions are a good design habit in many other languages, so
 is there any principle when writing python function?

It's hard to discuss in the abstract.  A function should perform a 
recognizable step in solving the program's problem.  If you prepared to 
write your program by describing each of several operations the program 
would have to perform, then you might go on to plan a function for each of 
the described operations.  The high-level functions can then be analyzed, 
and will probably lead to functions of their own.

Test-driven development encourages smaller functions that give you a better 
granularity of testing.  Even so, the testable functions should each perform 
one meaningful step of a more general problem.

 for example, how many lines should form a function?
Maybe as few as one.

def increase (x, a):
return x+a

is kind of stupid, but a more complicated line

def expand_template (bitwidth, defs):
'''Turn Run-Length-Encoded list into bits.'''
return np.array (sum (([bit]*(count*bitwidth) for count, bit in 
defs), []), np.int8)

is the epitome of intelligence.  I wrote it myself.  Even increase might be 
useful:

def increase (x, a):
return x + a * application_dependent_quantity

`increase` has become a meaningful operation in the imaginary application 
we're discussing.


For an upper bound, it's harder to say.  If you read to the end of a 
function and can't remember how it started, or what it did in between, it's 
too big.  If you're reading on your favourite screen, and the end and the 
beginning are more than one page-scroll apart, it might be too big.  If it's 
too big, factoring it into sub-steps and making functions of some of those 
sub-steps is the fix.

Mel.

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


Re: try... except with unknown error types

2011-08-19 Thread Mel
xDog Walker wrote:
 On Friday 2011 August 19 12:09, Yingjie Lin wrote:
[ ... ]
 Does anyone know what error type I should put after the except statement?
 or even better: is there a way not to specify the error types? Thank you.
 
 You probably need to import urllib2 before you can use urllib2.HTTPError.
 
 Otherwise, you can try using the base class:
 
 except Exception, e:

There are maybe better base classes to use.  Running the interpreter:
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) 
[GCC 4.4.3] on linux2
Type help, copyright, credits or license for more information.
 import urllib2
 help (urllib2.HTTPError)

will show you

class HTTPError(URLError, urllib.addinfourl)
 |  Raised when HTTP error occurs, but also acts like non-error return
 |  
 |  Method resolution order:
 |  HTTPError
 |  URLError
 |  exceptions.IOError
 |  exceptions.EnvironmentError
 |  exceptions.StandardError
 |  exceptions.Exception
 |  exceptions.BaseException
 

So catching any of urllib2.HTTPError, urllib2.URLError, IOError, 
EnvironmentError, or StandardError will detect the exception -- with 
increasing levels of generality.

Mel.

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


Re: pairwise combination of two lists

2011-08-17 Thread Mel
Yingjie Lin wrote:
 I have two lists:
 
 li1 = ['a', 'b']
 li2 = ['1', '2']
 
 and I wish to obtain a list like this
 
 li3 = ['a1', 'a2', 'b1', 'b2']
 
 Is there a handy and efficient function to do this, especially when li1
 and li2 are long lists.
 I found zip() but it only gives [('a', '1'), ('b', '2')],  not exactly
 what I am looking for.

This seems to do it :

mwilson@tecumseth:~$ python
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) 
[GCC 4.4.3] on linux2
Type help, copyright, credits or license for more information.
 import itertools
 li1 = ['a', 'b']
 li2 = ['1', '2']
 map (lambda (x,y):x+y, list (itertools.product (li1, li2)))
['a1', 'a2', 'b1', 'b2']


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


Re: pairwise combination of two lists

2011-08-17 Thread Mel
Mel wrote:

 Yingjie Lin wrote:
 I have two lists:
 
 li1 = ['a', 'b']
 li2 = ['1', '2']
 
 and I wish to obtain a list like this
 
 li3 = ['a1', 'a2', 'b1', 'b2']
[ ... ]
 This seems to do it :
 
 mwilson@tecumseth:~$ python
 Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
 [GCC 4.4.3] on linux2
 Type help, copyright, credits or license for more information.
 import itertools
 li1 = ['a', 'b']
 li2 = ['1', '2']
 map (lambda (x,y):x+y, list (itertools.product (li1, li2)))
 ['a1', 'a2', 'b1', 'b2']


I have doubts about this in Python3, since tuple unpacking in a argument 
list isn't done there, and I don't think sum works on strings.  Some other 
function can probably be made to work.

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


Re: Observations on the three pillars of Python execution

2011-08-05 Thread Mel
Steven D'Aprano wrote:

 There may be some other obscure built-in type that includes code objects,
 but I can't imagine what it would be. I feel confident in saying that
 functions, and functions alone, contain code. Even methods are just
 wrappers around functions. Even built-in functions like len don't contain
 code! (Or at least, their code isn't accessible from Python.) Which makes
 sense, if you think about it: their code is part of the Python virtual
 machine, not the object.

Interesting question.  Iterators seem to have code objects:

Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) 
[GCC 4.4.3] on linux2
Type help, copyright, credits or license for more information.
 a = [1, 2, 3]
 b = (x for x in a)
 dir(b)
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', 
'__hash__', '__init__', '__iter__', '__name__', '__new__', '__reduce__', 
'__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', 
'__subclasshook__', 'close', 'gi_code', 'gi_frame', 'gi_running', 'next', 
'send', 'throw']
 for name in dir(b):
...   print name, type (getattr (b, name))
... 
__class__ type 'type'
__delattr__ type 'method-wrapper'
__doc__ type 'NoneType'
__format__ type 'builtin_function_or_method'
__getattribute__ type 'method-wrapper'
__hash__ type 'method-wrapper'
__init__ type 'method-wrapper'
__iter__ type 'method-wrapper'
__name__ type 'str'
__new__ type 'builtin_function_or_method'
__reduce__ type 'builtin_function_or_method'
__reduce_ex__ type 'builtin_function_or_method'
__repr__ type 'method-wrapper'
__setattr__ type 'method-wrapper'
__sizeof__ type 'builtin_function_or_method'
__str__ type 'method-wrapper'
__subclasshook__ type 'builtin_function_or_method'
close type 'builtin_function_or_method'
gi_code type 'code'
gi_frame type 'frame'
gi_running type 'int'
next type 'method-wrapper'
send type 'builtin_function_or_method'
throw type 'builtin_function_or_method'


in the form of the gi_code attribute.  No idea what it's for, although no 
reason to believe it shouldn't be there.  (Very interesting demo you gave of 
primitive object creation.  I' awed.)

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


Re: I am fed up with Python GUI toolkits...

2011-07-20 Thread Mel
sturlamolden wrote:
 On 20 Jul, 11:59, Thomas Jollans t...@jollybox.de wrote:

 It is perfectly reasonable to be required to manually call some sort of
 destroy() method to tell the toolkit what you no longer want the user to
 see

 Yes, but not to avoid a memory leak.

OTOH, if you intend to re-use the Dialog object, it's not a memory leak.

Mel.

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


Re: Tabs -vs- Spaces: Tabs should have won.

2011-07-17 Thread Mel
Andrew Berg wrote:
 I should also mention that this mostly speculation on my part, and that
 I would love to hear from someone who develops for these devices.

There's a mailing list for Python scripting on Android -- 
List-Subscribe: http://groups.google.com/group/python-for-
android/subscribe?hl=en_US, mailto:python-for-
android+subscr...@googlegroups.com 
. Tends to be pretty detail-oriented.

Mel.

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


Re: Tabs -vs- Spaces: Tabs should have won.

2011-07-17 Thread Mel
Andrew Berg wrote:
 I should also mention that this mostly speculation on my part, and that
 I would love to hear from someone who develops for these devices.

There's a mailing list for Python scripting on Android -- 
List-Subscribe: http://groups.google.com/group/python-for-
android/subscribe?hl=en_US, mailto:python-for-
android+subscr...@googlegroups.com 
. Tends to be pretty detail-oriented.

Mel.

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


Re: None versus MISSING sentinel -- request for design feedback

2011-07-15 Thread Mel
Steven D'Aprano wrote:

 Well yes, but None is an explicit missing value too. The question I have
 is if I should support None as that value, or something else. Or if anyone
 can put a good case for it, both, or neither and so something completely
 different.

If it's any help, I think (some of?) the database interface packages already 
do just that, returning None when they find NULL fields.


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


Re: more advanced learning resources (code structure, fundamentals)

2011-07-07 Thread Mel
John [H2O] wrote:
[ ... ]
 What are the key points to the classes? Is it okay to reference or pass
 classes to instantiate a class? 

Yes.  The standard library does this in BaseHTTPServer (via its parent 
SocketServer.)  Maybe looks abstruse at the outset, but it's the natural way 
to assign a fresh message handler to a new input message.  Docs are via the 
Python Global Module Index, source is in some directory like
/usr/lib/python2.6/SocketServer.py , .../BaseHTTPServer.py , etc.

Mel.

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


Re: Implicit initialization is EXCELLENT

2011-07-06 Thread Mel
Ian Kelly wrote:

 On Wed, Jul 6, 2011 at 12:49 AM, Ulrich Eckhardt
 ulrich.eckha...@dominolaser.com wrote:
 Mel wrote:
 In wx, many of the window classes have Create methods, for filling in
 various attributes in two-step construction.  I'm not sure why,
 because it works so well to just supply all the details when the class
 is called and an instance is constructed.  Maybe there's some C++
 strategy that's being supported there.

 Just guessing, is it legacy, C-with-classes code rather than C++ code
 perhaps? Haven't looked at wx for a while. Such code typically lacks
 understanding of exceptions, which are the only way to signal failure
 from e.g. constructors.
 
 No, wx is C++ through and through.  For the why of it, see:
 
 http://wiki.wxpython.org/TwoStageCreation
 
 The More Details section is particularly illuminating.

Yes, it is.  Many thanks.

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


Re: Does hashlib support a file mode?

2011-07-06 Thread Mel
Phlip wrote:

 If I call m = md5() twice, I expect two objects.
 
 I am now aware that Python bends the definition of call based on
 where the line occurs. Principle of least surprise.

Actually, in

def file_to_hash(path, m = hashlib.md5()):

hashlib.md5 *is* called once; that is when the def statement is executed.

Later on, when file_to_hash gets called, the value of m is either used as 
is, as the default parameter, or is replaced for the duration of the call by 
another object supplied by the caller.

Mel.



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


Re: Implicit initialization is EXCELLENT

2011-07-05 Thread Mel
Steven D'Aprano wrote:
[ ... ]
 Python generally follows this design. Apart from files, I can't easily
 think off the top of my head of any types that require a separate
 open/start/activate call before they are usable. It's also relevant to
 tkinter, which will implicitly create a root window for you when needed.
 Since you can't do anything without a root window, I don't see the benefit
 in forcing the user to do so. When they need to learn about root windows,
 they will in their own good time.

In wx, many of the window classes have Create methods, for filling in 
various attributes in two-step construction.  I'm not sure why, because it 
works so well to just supply all the details when the class is called and an 
instance is constructed.  Maybe there's some C++ strategy that's being 
supported there.

Mel.

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


Re: Significant figures calculation

2011-06-28 Thread Mel
Erik Max Francis wrote:

 Chris Angelico wrote:
 On Tue, Jun 28, 2011 at 12:56 PM, Steven D'Aprano
 steve+comp.lang.pyt...@pearwood.info wrote:
 Zero sig figure: 0
 
 That's not really zero significant figures; without further
 qualification, it's one.
 
 Is 0.0 one sig fig or two?
 
 Two.
 
 (Just vaguely curious. Also curious as to
 whether a zero sig figures value is ever useful.)
 
 Yes.  They're order of magnitude estimates.  1 x 10^6 has one
 significant figure.  10^6 has zero.

By convention, nobody ever talks about 1 x 9.97^6 .

Mel.

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


Re: Significant figures calculation

2011-06-28 Thread Mel
Erik Max Francis wrote:

 Mel wrote:
 Erik Max Francis wrote:
 
 Chris Angelico wrote:
 On Tue, Jun 28, 2011 at 12:56 PM, Steven D'Aprano
 steve+comp.lang.pyt...@pearwood.info wrote:
 Zero sig figure: 0
 That's not really zero significant figures; without further
 qualification, it's one.

 Is 0.0 one sig fig or two?
 Two.

 (Just vaguely curious. Also curious as to
 whether a zero sig figures value is ever useful.)
 Yes.  They're order of magnitude estimates.  1 x 10^6 has one
 significant figure.  10^6 has zero.
 
 By convention, nobody ever talks about 1 x 9.97^6 .
 
 Not sure what the relevance is, since nobody had mentioned any such thing.
 
 If it was intended as a gag, I don't catch the reference.

I get giddy once in a while.. push things to limits.  It doesn't really mean 
anything.  The point was that it's only the 2 in a number like 2e6 that is 
taken to have error bars.  The 6 is always an absolute number.  As is the 10 
in 2*10**6.  The thought also crossed my mind of a kind of continued 
fraction in reverse -- 2e1.3e.7 .  I managed to keep quiet about that one.

Mel.

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


Re: writable iterators?

2011-06-22 Thread Mel
Steven D'Aprano wrote:

 On Wed, 22 Jun 2011 15:28:23 -0400, Neal Becker wrote:
 
 AFAICT, the python iterator concept only supports readable iterators,
 not write. Is this true?
 
 for example:
 
 for e in sequence:
   do something that reads e
   e = blah # will do nothing
 
 I believe this is not a limitation on the for loop, but a limitation on
 the python iterator concept.  Is this correct?
 
 Have you tried it? e = blah certainly does not do nothing, regardless
 of whether you are in a for loop or not. It binds the name e to the value
 blah.
 
 seq = [1, 2]
 for e in seq:
 ... print(e)
 ... e = 42
 ... print(e)
 ...
 1
 42
 2
 42
 
 
 I *guess* that what you mean by writable iterators is that rebinding e
 should change seq in place, i.e. you would expect that seq should now
 equal [42, 42]. Is that what you mean? It's not clear.
 
 Fortunately, that's not how it works, and far from being a limitation,
 it would be *disastrous* if iterables worked that way. I can't imagine
 how many bugs would occur from people reassigning to the loop variable,
 forgetting that it had a side-effect of also reassigning to the iterable.
 Fortunately, Python is not that badly designed.

And for an iterator like

def things():
yield 1
yield 11
yield 4
yield 9

I don't know what it could even mean.

Mel.

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


Re: How can I speed up a script that iterates over a large range (600 billion)?

2011-06-21 Thread Mel
John Salerno wrote:
 I'm working on the Project Euler exercises and I'm stumped on problem
 3:
 
 What is the largest prime factor of the number 600851475143 ?
[ ... ]
 Here is what I have so far. Initially the get_factors function just
 iterated over the entire range(2, n + 1), but since a number can't
 have a factor greater than half of itself, I tried to shorten the
 range by doing range(2, n //2), but that still leaves 300 billion
 numbers to go through.
 
 def get_factors(number):
 factors = [number]
 
 for n in range(2, number // 2):
 if number % n == 0:
 factors.append(n)
 
 return factors
 
 
 def get_primes(number_list):
 primes = number_list[:]
 
 for n in number_list:
 for x in range(2, n):
 if n % x == 0:
 primes.remove(n)
 break
 
 return primes
 
 
 print(max(get_primes(get_factors(600851475143
 
 
 Also, I want to make it clear that I DO NOT WANT THE ANSWER. I really
 want to solve this myself, but the reason I'm asking about it is to
 see if there really is some way to change this code so that it can get
 an answer in less than one minute, as the website says should be
 possible. A hint about what I need to do would be nice, but not an
 answer. I just don't see any way to get the factors without iterating
 over the entire range of values, though.

It certainly can be done faster.  I ran it against the factor finder that I 
wrote, and it popped up the answer

mwilson@tecumseth:~$ bin/factors.py 600851475143
71 839 1471 ...

before I could glance at my watch.  factors.py works, as does yours, by 
testing for small factors first, but it divides them out as it goes, so it 
tends to do its work on smallish numbers.  And since the smallest factors 
are taken out as soon as possible, they have to be the prime ones.

Good hunting,   Mel.

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


Re: Handling import errors

2011-06-21 Thread Mel
Guillaume Martel-Genest wrote:

 What is the pythonic way to handle imports error? What is bugging me
 is that the imports can't be inside a function (because I use them in
 different places in the script and thus they have to be in the global
 scope).

Actually, you can if you declare them global:

Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) 
[GCC 4.4.3] on linux2
Type help, copyright, credits or license for more information.
 def f():
... global os
... import os
... 
 dir (os)
Traceback (most recent call last):
  File stdin, line 1, in module
NameError: name 'os' is not defined
 f()
 dir (os)
['EX_CANTCREAT', 'EX_CONFIG', 'EX_DATAERR', 'EX_IOERR', 'EX_NOHOST', 
'EX_NOINPUT', 'EX_NOPERM', 'EX_NOUSER', 'EX_OK', 'EX_OSERR', 'EX_OSFILE', 
'EX_PROTOCOL', 'EX_SOFTWARE', 'EX_TEMPFAIL', 'EX_UNAVAILABLE', 'EX_USAGE', 
'F_OK', 'NGROUPS_MAX', 'O_APPEND', 'O_ASYNC', 'O_CREAT', 'O_DIRECT', 
'O_DIRECTORY', 'O_DSYNC', 'O_EXCL', 'O_LARGEFILE', 'O_NDELAY', 'O_NOATIME', 
'O_NOCTTY', 'O_NOFOLLOW', 'O_NONBLOCK

etc.

Mel.

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


Re: sorry, possibly too much info. was: Re: How can I speed up a script that iterates over a large range (600 billion)?

2011-06-21 Thread Mel
John Salerno wrote:

 ::sigh:: Well, I'm stuck again and it has to do with my get_factors
 function again, I think. Even with the slight optimization, it's
 taking forever on 20! (factorial, not excitement)  :) It's frustrating
 because I have the Python right, but I'm getting stuck on the math.
 
 The problem:
 
 What is the smallest positive number that is evenly divisible by all
 of the numbers from 1 to 20?
 
 
 
 Here's the function (it's in the problem3.py file, hence the import
 below):
 
 import math
 
 def get_factors(number):
 factors = []
 
 for n in range(2, int(math.sqrt(number))):
 if number % n == 0:
 factors.append(n)
 factors.append(number // n)
 
 return factors
 
 And here's my new script for the new exercise:
 
 import math
 from problem3 import get_factors
 
 max_num = 20
 n = math.factorial(max_num)
 factors = get_factors(n)
 div_all = []
 
 for x in factors:
 for y in range(2, max_num+1):
 if x % y != 0:
 break
 elif y == max_num:
 div_all.append(x)
 
 print(min(div_all))
 
 It could easily be that I'm simply approaching it all wrong. I just
 thought that maybe using the factorial of the highest number in the
 range (in this case, 20) would be an easy way of finding which numbers
 to test.

These are almost trick questions in a way, because of the math behind 
them.  If the question were What is the tallest high-school student in 
Scranton, PA? then searching a population for the property would be the 
only way to go.  BUT you can also build up the answer knowing the 
factorization of all the numbers up to 20.

Mel.

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


Re: What's the best way to write this base class?

2011-06-20 Thread Mel
John Salerno wrote:

 On Jun 19, 8:52 pm, Chris Kaynor ckay...@zindagigames.com wrote:
 
 Having a character class (along with possibly player character,
 non-player character, etc), make sense; however you probably want to make
 stuff like health, resources, damage, and any other attributes not be
 handles by any classes or inheritance in order to allow you to make such
 data-driven (ie, read from a file). Doing so makes the game much more
 extendable: using classes, you are likely limited to 5 or 'combinations
 and a few developers (plus, any designers need to know programming).

 A basic way to determine between using subclasses over a data driven
 approach is: is there significantly different back-end behavior or merely
 attribute differences.
 
 Can you give a basic example of how this data-driven approach would
 work? You don't have to provide any code, just a description would be
 helpful. Such as, do I create a data file per character, and then have
 each character instance read/write to that file? Is it good to have so
 many files open at once, or would they only need to be read, closed,
 then opened again at the end to write?

Battle for Wesnoth is set up this way.  I don't know what the code does, but 
you can go wild creating new classes of character by mixing up new 
combinations of attribute settings in new configuration files, and injecting 
them into the standard game config files.

AFAIK you are stuck with the attributes the game is programmed for.  I've 
seen no way to create a new dimension for the game -- Conversation, for 
instance, with currently unknown attributes like vocabulary or tone.

Mel.

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


Re: What's the best way to write this base class?

2011-06-18 Thread Mel
John Salerno wrote:
[ ... ]
 1)
 class Character:
 def __init__(self, name, base_health=50, base_resource=10):
 self.name = name
 self.health = base_health
 self.resource = base_resource
 
 2)
 class Character:
 base_health = 50
 base_resource = 10
 def __init__(self, name):
 self.name = name
 self.health = base_health
 self.resource = base_resource
 
 3)
 BASE_HEALTH = 50
 BASE_RESOURCE = 10
 class Character:
 def __init__(self, name):
 self.name = name
 self.health = BASE_HEALTH
 self.resource = BASE_RESOURCE

For completeness, there's also 4)

Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) 
[GCC 4.4.3] on linux2
Type help, copyright, credits or license for more information.
 class Character (object):
... health = 50
... def __init__ (self, name):
... self.name = name
... print self.name, self.health
... 
 Character ('Eunice')
Eunice 50


where the class attribute is used until it's overridden in the instance.

Mel.

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


Re: How to form a dict out of a string by doing regex ?

2011-06-15 Thread Mel
Satyajit Sarangi wrote:

 
 
 data = GEOMETRYCOLLECTION (POINT (-8.96484375
 -4.130859375000), POINT (2.021484375000 -2.63671875),
 POINT (-1.40625000 -11.162109375000), POINT
 (-11.95312500,-10.89843750), POLYGON
 ((-21.62109375 1.845703125000,2.46093750
 2.197265625000, -18.98437500 -3.69140625,
 -22.67578125 -3.33984375, -22.14843750
 -2.63671875, -21.62109375
 1.845703125000)),LINESTRING (-11.95312500
 11.337890625000, 7.73437500 11.513671875000,
 12.30468750 2.548828125000, 12.216796875000
 1.669921875000, 14.501953125000 3.955078125000))
 
 This is my string .
 How do I traverse through it and form 3 dicts of Point , Polygon and
 Linestring containing the co-ordinates ?

Except for those space-separated number pairs, it could be a job for some 
well-crafted classes (e.g. `class GEOMETRYCOLLECTION ...`, `class POINT 
...`) and eval.

My approach would be to use a loop with regexes to recognize the leading 
element and pick out its arguments, then use the string split and strip 
methods beyond that point.  Like (untested):

recognizer = re.compile (r'(?(POINT|POLYGON|LINESTRING)\s*\(+(.*?)\)+,(.*)')
# regex is not good with nested brackets, 
# so kill off outer nested brackets..
s1 = 'GEOMETRYCOLLECTION ('
if data.startswith (s1):
data = data (len (s1):-1)

while data:
match = recognizer.match (data)
if not match:
break   # nothing usable in data
## now the matched groups will be:
## 1: the keyword
## 2: the arguments inside the smallest bracketed sequence
## 3: the rest of data
##  so use str.split and str.match to pull out the individual arguments,
## and lastly
data = match.group (3)

This is all from memory.  I might have got some details wrong in recognizer.

Mel.

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


Re: Dynamic Zero Padding.

2011-06-07 Thread Mel
Friedrich Clausen wrote:
 I want to print some integers in a zero padded fashion, eg. :
 
 print(Testing %04i % 1)
 Testing 0001
 
 but the padding needs to be dynamic eg. sometimes %05i, %02i or some
 other padding amount. But I can't insert a variable into the format
 specification to achieve the desirable padding.
 
 I would be much obliged if someone can give me some tips on how to
 achieve a variably pad a number.

:)

('%%0%dd' % (pads,)) % (n,)

Probably be good to wrap it in a function.  It looks kind of obscure as it 
is.

Mel.

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


Re: Lambda question

2011-06-04 Thread Mel
jyoun...@kc.rr.com wrote:

 I was surfing around looking for a way to split a list into equal
 sections.  I came upon this algorithm:
  
 f = lambda x, n, acc=[]: f(x[n:], n, acc+[(x[:n])]) if x else acc
 f(Hallo Welt, 3)
 ['Hal', 'lo ', 'Wel', 't']
  
 http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-
evenly-s
 ized-chunks-in-python/312644
  
 It doesn't work with a huge list, but looks like it could be handy in
 certain
 circumstances.  I'm trying to understand this code, but am totally lost. 
 I know a little bit about lambda, as well as the ternary operator, but how
 does this part work:
  
 f('dude'[3:], 3, []+[('dude'[:3])])
 ['dud', 'e']
  
 Is that some sort of function call, or something else?  I'm guessing it
 works recursively?

Yeah, recursive.

f('dude', 3) 

evaluates to

f('e', 3, []+['dud']) if 'dude' else []

which evaluates to

f('', 3, []+['dud']+['e']) if 'e' else []+['dud']

which evaluates to

[]+['dud']+['e']

because the if...else finally takes the second branch since the x value is 
now an empty string.  

I've left the list additions undone .. tracing the actual data objects would 
show plain lists.  One of the disadvantages of lambdas is that you can't 
stick trace printouts into them to clarify what's happening.  Rewriting the 
thing as a plain def function would be instructive.

Mel.



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


Re: scope of function parameters

2011-05-29 Thread Mel
Henry Olders wrote:

 I just spent a considerable amount of time and effort debugging a program.
 The made-up code snippet below illustrates the problem I encountered:
 
 def main():
 a = ['a list','with','three elements']
 print a
 print fnc1(a)
 print a
 
 def fnc1(b):
 return fnc2(b)
 
 def fnc2(c):
 c[1] = 'having'
 return c
 
 This is the output:
 ['a list', 'with', 'three elements']
 ['a list', 'having', 'three elements']
 ['a list', 'having', 'three elements']
 
 I had expected the third print statement to give the same output as the
 first, but variable a had been changed by changing variable c in fnc2.
 
 It seems that in Python, a variable inside a function is global unless
 it's assigned. This rule has apparently been adopted in order to reduce
 clutter by not having to have global declarations all over the place.
 
 I would have thought that a function parameter would automatically be
 considered local to the function. It doesn't make sense to me to pass a
 global to a function as a parameter.

It doesn't look like a question of local or global.  fnc2 is passed a 
container object and replaces item 1 in that container.  You see the results 
when fnc2 prints the object it knows as `c`, and you see again when main 
prints the object it knows as `a`.  Python doesn't pass parameters by 
handing around copies that can be thought of as local or global.  Python 
passes parameters by binding objects to names in the callee's namespace.  In 
your program the list known as `a` in main is identically the same list as 
the one known as `c` in fnc2, and what happens happens.

Mel.

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


Re: bug in str.startswith() and str.endswith()

2011-05-27 Thread Mel
Terry Reedy wrote:

 To me, that says pretty clearly that start and end have to be
 'positions', ie, ints or other index types. So I would say that the
 error message is a bug. I see so reason why one would want to use None
 rather that 0 for start or None rather than nothing for end.

If you're trying to wrap a call to startswith in a function that looks 
like startswith, there's no easy way to pass in the information that your 
caller wants the default parameters.  The case I ran into was

def wrapped_range (start, stop=None, span=None):
do_some_things()
result = range (start, stop, span)  # range doesn't(/didn't) accept this
return result
   

Tne answer in that case was to take *args as the parameter to wrapped_range 
and count arguments to distinguish between the different calls to range. 

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


Re: Python's super() considered super!

2011-05-27 Thread Mel
sturlamolden wrote:

 I really don't like the Python 2 syntax of super, as it violates
 the DRY principle: Why do I need to write super(type(self),self)
 when super() will do? Assuming that 'self' will always be named
 'self' in my code, I tend to patch __builtins__.super like this:
 
 import sys
 def super():
 self = sys._getframe().f_back.f_locals['self']
 return __builtins__.super(type(self),self)
 
 This way the nice Python 3.x syntax can be used in Python 2.x.

Python causes trouble by letting the users get at the internals, but things 
like this make it worthwhile.

Mel.

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


Re: bug in str.startswith() and str.endswith()

2011-05-26 Thread Mel
Ethan Furman wrote:

 I've tried this in 2.5 - 3.2:
 
 -- 'this is a test'.startswith('this')
 True
 -- 'this is a test'.startswith('this', None, None)
 Traceback (most recent call last):
File stdin, line 1, in module
 TypeError: slice indices must be integers or None or have an __index__
 method
 
 The 3.2 docs say this:
 
 str.startswith(prefix[, start[, end]])
 Return True if string starts with the prefix, otherwise return False.
 prefix can also be a tuple of prefixes to look for. With optional start,
 test string beginning at that position. With optional end, stop
 comparing string at that position
 
 str.endswith(suffix[, start[, end]])
 Return True if the string ends with the specified suffix, otherwise
 return False. suffix can also be a tuple of suffixes to look for. With
 optional start, test beginning at that position. With optional end, stop
 comparing at that position.
 
 Any reason this is not a bug?

It's a wart at the very least.  The same thing happened in Python2 with 
range and xrange; there seemed no way to explicitly pass default 
arguments.

Mel.

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


Re: Obtaining a full path name from file

2011-05-24 Thread Mel
Tim Golden wrote:

 On 24/05/2011 16:36, RVince wrote:
 s = C:\AciiCsv\Gravity_Test_data\A.csv
 f = open(s,r)

 How do I obtain the full pathname given the File, f? (which should
 equal C:\AciiCsv\Gravity_Test_data). I've tried all sorts of stuff
 and am just not finding it. Any help greatly appreciated !
 
 You're going to kick yourself:
 
 f.name

There's trouble there, though:

Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) 
[GCC 4.4.3] on linux2
Type help, copyright, credits or license for more information.
 f = open ('xyzzy.txt')
 f.name
'xyzzy.txt'
 import os
 os.getcwd()
'/home/mwilson'
 os.chdir('sandbox')
 f.name
'xyzzy.txt'


If you open a file and don't get a full path from os.path.abspath right 
away, the name in the file instance can get out-of-date.

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


Re: What other languages use the same data model as Python?

2011-05-09 Thread Mel
Steven D'Aprano wrote:

 It's not an awful model for Python: a name binding a = obj is equivalent
 to sticking a reference (a pointer?) in box a that points to obj.
 Certainly there are advantages to it.
 
 But one problem is, the model is ambiguous with b = a. You've drawn
 little boxes a and b both pointing to the big box (which I deleted for
 brevity). But surely, if a = 1234 creates a reference from a to the big
 box 1234, then b = a should create a reference from b to the box a?

:) There's a way around that too.  Describe literals as magic names or 
Platonic names that are bound to objects in ideal space.  I actually 
considered that for a while as a way of explaining to newbs why the 
characters in a string literal could be different from the characters in the 
string value.  This would probably have troubles of its own; I never took it 
through the knock-down drag-out disarticulation that would show what the 
problems were.

Mel.

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


Re: What other languages use the same data model as Python?

2011-05-05 Thread Mel
John Nagle wrote:
 On 5/4/2011 5:46 PM, harrismh777 wrote:
 Or, as stated earlier, Python should not allow 'is' on immutable objects.
 
 A reasonable compromise would be that is is treated as == on
 immutable objects.

I foresee trouble testing among float(5), int(5), Decimal(5) ...

Mel.

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


Re: What other languages use the same data model as Python?

2011-05-05 Thread Mel
Tim Roberts wrote:
 That is not an instance of passing an int by reference.  That is an
 instance of passing an int * by value.  The fact that the parameter a
 in BumpMe happens to be an address is completely irrelevent to the
 definition of the parameter passing mechanism.
 
 C has pass-by-value, exclusively.  End of story.

Trouble with Turing-complete languages.  If it can be done, you can convince 
a Turing-complete language to do it -- somehow.

PL/I was the converse.  All parameters were passed by reference, so with

some_proc (rocks);

the code in some_proc would be working with the address of rocks.  If you 
wanted pass-by-value you wrote

some_proc ((rocks));

whereupon the compiler would pass in by reference an unnamed temporary 
variable whose value was the expression `(rocks)`.  I suspect the compiler I 
used avoided FORTRAN's troubles the same way.  Your function could corrupt 
*a* 4, but it wouldn't corrupt the *only* 4.

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


Re: What other languages use the same data model as Python?

2011-05-05 Thread Mel
Steven D'Aprano wrote:

 Some day, we'll be using quantum computers without memory addresses, [ ... 
] it will still be possible to
 represent data indirectly via *some* mechanism.

:)  Cool!  Pass-by-coincidence!  And Python 3 already has dibs on the 
'nonlocal' keyword!

Mel.

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


Re: What other languages use the same data model as Python?

2011-05-03 Thread Mel
Hans Georg Schaathun wrote:

 On 01 May 2011 08:45:51 GMT, Steven D'Aprano
   steve+comp.lang.pyt...@pearwood.info wrote:
 :  Python uses a data model of name binding and call by object (also
 :  known as call by sharing). I trust I don't need to define my terms,
 :  but just in case:
 
 Without having the time to get my hand around exactly what this means:
 Simula has three ways of transmitting arguments, namely transmission
 by name, by value, and by reference.  Is transmission by name the same
 as call by object?  Anyway, I have never seen anyone counting more than
 three ways of doing this ...

To illustrate the neither-fish-nor-fowl nature of Python calls:

mwilson@tecumseth:~$ python
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) 
[GCC 4.4.3] on linux2
Type help, copyright, credits or license for more information.
 def identify_call (a_list):
...   a_list[0] = If you can see this, you don't have call-by-value
...   a_list = [If you can see this, you have call-by-reference]
... 
 my_list = [None]
 identify_call (my_list)
 my_list
[If you can see this, you don't have call-by-value]



so it's neither call-by-value nor call-by-reference as (e.g.) C or PL/I 
programming would have it (don't know about Simula, so I am off topic, 
actually.)  It's not so wrong to think of Python's parameter handling as 
ordinary assignments from outer namespaces to an inner namespace.

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


Re: Why do directly imported variables behave differently than those attached to imported module?

2011-05-03 Thread Mel
Dun Peal wrote:

 Hi!
 
 Here's the demonstrating code:
 
 # module foo.py
 var = 0
 
 def set():
 global var
 var = 1
 
 Script using this module:
 
 import foo
 from foo import *
 
 print var, foo.var
 set()
 print var, foo.var
 
 Script output:
 
 0 0
 0 1
 
 Apparently, the `var` we imported from `foo` never got set, but
 `foo.var` on the imported `foo` - did. Why?

They're different because -- they're different.  `foo.var` is defined in the 
namespace of the foo module.  Introspectively, you would access it as 
`foo.__dict__['var']` .

Plain `var` is in your script's namespace so you could access it as 
`globals()['var']` .  The values given to the vars are immutable integers, 
so assignment works by rebinding.  The two different bindings in 
foo.__dict__ and globals() get bound to different integer objects.

Note too the possible use of `globals()['foo'].__dict__['var'] .  (Hope 
there are no typos in this post.)

Mel.

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


Re: Input() in Python3

2011-04-25 Thread Mel
Westley Martínez wrote:

 On Fri, Apr 22, 2011 at 10:08:20AM -0400, Mel wrote:
[ ... ]
 But sys.exit() doesn't return a string.  My fave is
 
 Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
 [GCC 4.4.3] on linux2
 Type help, copyright, credits or license for more information.
  import sys
  a = int (input ('enter a number '))
 enter a number sys.setrecursionlimit(1)
 Exception RuntimeError: 'maximum recursion depth exceeded while calling a
 Python object' in type 'exceptions.RuntimeError' ignored
[ ... ]

 What?

I guess sys.setrecursionlimit was meant to be called with a large number.  
Calling it with a small one roadblocks the interpreter.  Luckily, there can 
be just enough room to call setrecursionlimit again with something 
reasonable to get it all back.  Not enough room for `eval 
(sys.setrecursionlimit (2000)`, though.

Mel.

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


Re: learnpython.org - an online interactive Python tutorial

2011-04-22 Thread Mel
harrismh777 wrote:

 Heiko Wundram wrote:
 The difference between strong typing and weak typing is best described
 by:

 Python 2.6.5 (r265:79063, Jun 12 2010, 17:07:01)
 [GCC 4.3.4 20090804 (release) 1] on cygwin
 Type help, copyright, credits or license for more information.
   1+'2'
 Traceback (most recent call last):
File stdin, line 1, inmodule
 TypeError: unsupported operand type(s) for +: 'int' and 'str'
 
 
 Yes. And you have managed to point out a serious flaw in the overall
 logic and consistency of Python, IMHO.
 
 Strings should auto-type-promote to numbers if appropriate.

Appropriate is the problem.  This is why Perl needs two completely 
different kinds of comparison -- one that works as though its operands are 
numbers, and one that works as though they're strings.  Surprises to the 
programmer who picks the wrong one.

Mel.

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


Re: Input() in Python3

2011-04-22 Thread Mel
Westley Martínez wrote:
 On Fri, Apr 22, 2011 at 04:49:19PM +1000, Chris Angelico wrote:

 U NO. NO NO NO. What if someone enters os.exit() as their
 number? You shouldn't eval() unchecked user input!
 
 Chris Angelico
 
 Right, there's no way to check you're getting a number, however using:
 
 a = int(input('enter a number  ')) # use float() for floats
 
 will raise an exception if it can't convert the string.

But sys.exit() doesn't return a string.  My fave is

Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) 
[GCC 4.4.3] on linux2
Type help, copyright, credits or license for more information.
 import sys
 a = int (input ('enter a number '))
enter a number sys.setrecursionlimit(1)
Exception RuntimeError: 'maximum recursion depth exceeded while calling a 
Python object' in type 'exceptions.RuntimeError' ignored
Exception RuntimeError: 'maximum recursion depth exceeded while calling a 
Python object' in type 'exceptions.RuntimeError' ignored
Error in sys.excepthook:
RuntimeError: maximum recursion depth exceeded

Original exception was:
Traceback (most recent call last):
  File stdin, line 1, in module
RuntimeError: maximum recursion depth exceeded while calling a Python object
 int (0)
Exception RuntimeError: 'maximum recursion depth exceeded while calling a 
Python object' in type 'exceptions.RuntimeError' ignored
Exception RuntimeError: 'maximum recursion depth exceeded while calling a 
Python object' in type 'exceptions.RuntimeError' ignored
Error in sys.excepthook:
RuntimeError: maximum recursion depth exceeded

Original exception was:
Traceback (most recent call last):
  File stdin, line 1, in module
RuntimeError: maximum recursion depth exceeded while calling a Python object
 


Mel.

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


Re: List comprehension vs filter()

2011-04-20 Thread Mel
Chris Angelico wrote:
 On Wed, Apr 20, 2011 at 5:16 PM, Tim Roberts t...@probo.com wrote:
 You can solve this through the common lamba idiom of a closure:

 lst=filter(lambda x,posttype=posttype: x[type].lower()==posttype,lst)
 
 Seems a little odd, but sure. I guess this means that a function's
 default arguments are evaluated in the parent context, but the body is
 evaluated in its own context?

The operation of calling a function has to evaluate arguments provided in 
the caller's namespace and assign them to variables in the called function's 
namespace.  Yes.

Mel.

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


Re: dictionary size changed during iteration

2011-04-20 Thread Mel
Laszlo Nagy wrote:

 Given this iterator:
 
 class SomeIterableObject(object):
  
  
 
  def __iter__(self):
  ukeys = self.updates.keys()
  for key in ukeys:
  if self.updates.has_key(key):
  yield self.updates[key]
  for rec in self.inserts:
  yield rec
  
  
 
 How can I get this exception:
 
 RuntimeError: dictionary changed size during iteration
 
 
 It is true that self.updates is being changed during the iteration. But
 I have created the ukeys variable solely to prevent this kind of
 error. Here is a proof of correctness:
 
  d = {1:1,2:2}
  k = d.keys()
  del d[1]
  k
 [1, 2]
  k is d.keys()
 False
 
 So what is wrong with this iterator? Why am I getting this error message?

`ukeys` isn't a different dictionary from `self.updates.keys`  I'ts merely 
another name referring to the same dict object.  I think

ukeys = dict (self.updates.keys)

would do what you want.

Mel.

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


Re: dictionary size changed during iteration

2011-04-20 Thread Mel
Mel wrote:
 Laszlo Nagy wrote:
 `ukeys` isn't a different dictionary from `self.updates.keys`  I'ts merely
 another name referring to the same dict object.  I think
 
 ukeys = dict (self.updates.keys)
 
 would do what you want.

Sorry.  Belay that.  Thought I'd had enough coffee.

Mel.

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


Re: Feature suggestion -- return if true

2011-04-12 Thread Mel
Paul Rubin wrote:

 zildjohn01 zildjoh...@gmail.com writes:
 _temp = expr
 if _temp: return _temp
 
 I'm trying to figure out a context where you'd even want that, and I'm
 thinking that maybe it's some version of a repeat-until loop?  Python
 doesn't have repeat-until and it's been proposed a few times.

I can imagine

return? tree_node.left
return? tree_node.right

although my real code would probably be more like

if tree_node.left is not None:
return left, tree_node.left
if tree_node.right is not None:
return right, tree_node.right

where adding the left and right markers makes the return? feature 
impossible to use.

The proposed feature reminds me of the `zod` function (was that the actual 
name?) that returned 0 rather than bringing on a ZeroDivideError.  It would 
cement a strange corner-case into the language.

Mel.

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


Re: Argument of the bool function

2011-04-10 Thread Mel
Chris Angelico wrote:

 Who would use keyword arguments with a function that takes only one arg
 anyway?

It's hard to imagine.  Maybe somebody trying to generalize function calls 
(trying to interpret some other language using a python program?)

# e.g. input winds up having the effect of ..
function = bool
name = 'x'
value = 'the well at the end of the world'
## ...
actions.append ((function, {name:value}))
## ...
for function, args in actions:
results.append (function (**args))

Not something I, for one, do every day.  But regularity in a language is 
good when you can get it, especially for abstract things like that.

I can sort of guess that `dir` was perhaps coded in C for speed and doesn't 
spend time looking for complicated argument lists.

Python is a pragmatic language, so all the rules come pre-broken.


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


Re: Argument of the bool function

2011-04-08 Thread Mel
candide wrote:
 About the standard function bool(), Python's official documentation 
 tells us the following :

 bool([x])
 Convert a value to a Boolean, using the standard truth testing procedure.

 In this context, what exactly a value is referring to ?

 For instance,
   x=42
   bool(x=5)
 True
  

Cute.  What's happening here is that `x=5` isn't really an expression. 
It's passing a value to the named parameter `x`, specified in the
definition of `bool`.  Try it with something else:

Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) 
[GCC 4.4.3] on linux2
Type help, copyright, credits or license for more information.
 bool(y=5)
Traceback (most recent call last):
  File stdin, line 1, in module
TypeError: 'y' is an invalid keyword argument for this function



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


Re: [OT] Free software versus software idea patents

2011-04-07 Thread Mel
harrismh777 wrote:
 Steven D'Aprano wrote:

   At this point Microsoft has absolutely nothing to offer the computer
   science community at large except bzillions of euros ( or dollars ) of
   wasteful litigation and head-ache.
 Do you have an example of this wasteful litigation?

  You have to be kidding, right?  Check *any* of the sites I listed 
 above and read about it... software idea patent litigation is a business 
 now worth billions of dollars per year. 

One of the premier sites:

http://www.groklaw.net/

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


Re: is python 3 better than python 2?

2011-04-05 Thread Mel
neil wrote:

 what are the advantages? if it wasn't for python 3 breaking backwards
 compatibility would it be the better choice? 

IMHO the killer app for Python 3 is in more reasonable support for
foreign character sets (no matter where your are, at least one out of
the hundred-odd Unicode character sets is going to be foreign,) and
generally internationalized data processing.

Mel.

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


Re: TypeError: iterable argument required

2011-04-04 Thread Mel
Νικόλαος Κούρας wrote:

  iam getting the following error which i dont understand

  **
  163         # insert guest comments into database if form was
  submitted
    164         if @ in mail and comment not in (Σχολιάστε ή ρωτήστε
  με σχετικά, ):
    165                 try:
    166                         cursor.execute( '''INSERT INTO
  users(mail, comment) VALUES(%s, %s)''', (mail, comment) )
  mail = None, comment = None

  TypeError: iterable argument required
        args = ('iterable argument required',)


 In my original question can you explain to me what the meaning of the
 following error is?

 
 mail = None, comment = None
 TypeError: iterable argument required
   args = ('iterable argument required',)
 *

 Also i noticed that if i append a query string in the end of a url
 with the varibble mail attached like

 http://superhost.gr/hosting.html?mail=test

 then page hosting.html does load without any problem.

 If i remove the query string from the ned of the URL then i'am getting
 the error message i posted.

 So its not that the if condition is wrong but something happens with
 the form variable 'mail' .

My wild guess is that the trouble is in `if @ in mail` .  You can only
test somthing `in` something if the second thing is iterable.  So when
you don't supply a value via `?mail=' -- maybe the code that sets the
value of `mail` from the URL (code you don't show us) sets `mail=None`,
your server-side code blows up.  Things would be simpler if you included
a traceback in your error logging.

Mel.

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


Re: send function keys to a legacy DOS program

2011-03-29 Thread Mel
Alexander Gattin wrote:
 Another thing is that you may need to send key
 release after key press in order for the
 application to trigger the F5/F2/F7 event. I'm not
 sure what the scan codes for F5/F2/F7 releases
 are, but think that they may be:

 F5: 0xBF
 F2: 0xBC
 F7: 0xC1

True.  The key-release codes are the key-press codes (the key numbers)
but with the high-order bit set.

Mel.

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


Re: Guido rethinking removal of cmp from sort method

2011-03-24 Thread Mel
Carl Banks wrote:

 On Mar 23, 1:38 pm, Paul Rubin no.em...@nospam.invalid wrote:
 Well, I thought it was also to get rid of 3-way cmp in general, in favor
 of rich comparison.

 Supporting both __cmp__ and rich comparison methods of a class does
 add a lot of complexity.  The cmp argument of sort doesn't.

 The cmp argument doesn't depend in any way on an object's __cmp__
 method, so getting rid of __cmp__ wasn't any good readon to also get
 rid of the cmp argument; their only relationship is that they're
 spelled the same.  Nor is there any reason why cmp being a useful
 argument of sort should indicate that __cmp__ should be retained in
 classes.

I would have thought that the upper limit of cost of supporting cmp= and
key= would be two different internal front-ends to the internal
internal sort.

Mel.

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


Re: Bounds checking

2011-03-18 Thread Mel
Jean-Michel Pichavant wrote:
 Martin De Kauwe wrote:

 Don't check for bounds, fix any bug in the code that would set your
 values out of bounds and use asserts while debugging.
[ ... ]
 def __setattr__(self, attribute, value):
if not self.funcTable.get(attribute, lambda x: True)(value):
sys.exit('error out of bound')
return object.__setattr(self, attribute, value)

Offhand, my only quibble is that sys.exit is not helpful for debugging.  
Much better to raise an error:

if not self.funcTable.get(attribute, lambda x: True)(value):
raise ValueError ('error out of bound')

or define a subclass of ValueError just for this purpose.  On error, the 
program will stop just as dead, but you'll get a trace.

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


Re: Coding and Decoding in Python

2011-03-17 Thread Mel
Wanderer wrote:

 I have a dll that to communicate with I need to send numeric codes. So
 I created a dictionary. It works in one direction in that I can
 address the key and get the value. But when the program returns the
 value I can't get the key. This code is very simple and I could use a
 list and the index except for the last value. Is there a better way to
 handle coding and decoding values to strings?
 
 QCam_Info = {
 'qinfCameraType' : 0,# Camera model (see
 QCam_qcCameraType)
 'qinfSerialNumber': 1,# Deprecated
 'qinfHardwareVersion'   : 2,# Hardware version
 'qinfFirmwareVersion'   : 3,# Firmware version
 'qinfCcd'  : 4,# CCD model (see
 QCam_qcCcd)
[ ... ]
 '_qinf_force32'   : 0x
 }

I handled this problem in a kind of cheap, nasty way with (untested)

for k, v in QCam_Info.items():
QCam_Info[v] = k

Then the dictionary lookups work both ways.

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


Re: PEP for module naming conventions

2011-03-17 Thread Mel
Tim Johnson wrote:

 I need to be better informed on naming conventions for modules.  For
 instance, I need to create a new module and I want to make sure that
 the module name will not conflict with any future or current python
 system module names.

COBOL in its golden years had a practice that reserved words were almost 
never hyphenated -- the few that were could be counted on the fingers of 
perhaps four hands and were mostly required paragraph names that were always 
used and hard to forget.

It might turn out well to specify that system module names will never 
contain more than, say, one underscore.  That way, nice descriptive 
application module names like 'analyzer_tool_utils' and such would always be 
safe to use.

Mel.

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


Re: my computer is allergic to pickles

2011-03-07 Thread Mel
Bob Fnord wrote:

 I want a portable data file (can be moved around the filesystem
 or copied to another machine and used), so I don't want to use
 mysql or postgres. I guess the sqlite approach would work, but
 I think it would be difficult to turn the tuples of strings and
 lists of strings and numbers into database table lines.

This is as hairy as it's ever got for me (untested):

def inserter (db, table_name, names, values):
query = 'INSERT INTO %s (%s) VALUES (%s)' % (table_name, ','.join 
(names), ','.join (['?'] * len (names)))
cur = db.cursor()
cur.execute (query, values)
cur.close()
#...
for v in all_value_triples:
inserter (db, 'some_table', ['f1', 'f2', 'f3'], v)

(or even write a bulk_inserter that took all_value_triples as an argument 
and moved the `for v in ...` inside the function.)

 Would a database in a file have any advantages over a file made
 by marshal or shelve?

Depends.  An sqlite3 database file is usable by programs not written in 
Python.

 I'm more worried about the fact that a python program in user
 space can bring down the computer!

Never been a problem in the programs I've written.

Mel.

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


Re: ImSim: Image Similarity

2011-03-07 Thread Mel
n00m wrote:

 But funny thing takes place.
 At first thought it's a false-positive: some modern South East
 Asian town and a lake somewhere in Russia, more than 100 years
 ago. Nothing similar in them?
 
 On both pics we see:
 -- a lot of water on foreground;
 -- a lot of blue sky at sunny mid-day;
 -- a bit of light white clouds in the sky;
 
 In short,
 the notion of similarity can be speculated about just endlessly.

Exactly.  That's the kind of similarity I would call valid.  That's what my 
algorithms, if I ever finished writing any, would be looking for.

Mel.

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


Re: ImSim: Image Similarity

2011-03-05 Thread Mel
n00m wrote:

 
 I uploaded a new version of the subject with a
 VERY MINOR correction in it. Namely, in line #55:
 
 print '%12s %7.2f' % (db[k][1], db[k][0] / 3600.0,)
 
 instead of
 
 print '%12s %7.2f' % (db[k][1], db[k][0] * 0.001,)
 
 I.e. I normalized it to base = 100.
 Now the values of similarity can't be greater than 100
 and can be treated as some regular percents (%%).
 
 Also, due to this change, the *empirical* threshold of
 system alarmity moved down from number 70 to 20%.
 
   bears2.jpg
 
   bears2.jpg0.00
   bears3.jpg   15.37
   bears1.jpg   19.13
 sky1.jpg   23.29
 sky2.jpg   23.45
  ff1.jpg   25.37
lake1.jpg   26.43
   water1.jpg   26.93
  ff2.jpg   28.43
   roses1.jpg   31.95
   roses2.jpg   36.12

I'd like to see a *lot* more structure in there, with modularization, so the 
internal functions could be used from another program.  Once I'd figured out 
what it was doing, I had this:


from PIL import Image
from PIL import ImageStat

def row_column_histograms (file_name):
'''Reduce the image to a 5x5 square of b/w brightness levels 0..3
Return two brightness histograms across Y and X
packed into a 10-item list of 4-item histograms.'''
im = Image.open (file_name)
im = im.convert ('L')   # convert to 8-bit b/w
w, h = 300, 300
im = im.resize ((w, h))
imst = ImageStat.Stat (im)
sr = imst.mean[0]   # average pixel level in layer 0
sr_low, sr_mid, sr_high = (sr*2)/3, sr, (sr*4)/3
def foo (t):
if t  sr_low: return 0
if t  sr_mid: return 1
if t  sr_high: return 2
return 3
im = im.point (foo) # reduce to brightness levels 0..3
yhist = [[0]*4 for i in xrange(5)]
xhist = [[0]*4 for i in xrange(5)]
for y in xrange (h):
for x in xrange (w):
k = im.getpixel ((x, y))
yhist[y / 60][k] += 1
xhist[x / 60][k] += 1
return yhist + xhist


def difference_ranks (test_histogram, sample_histograms):
'''Return a list of difference ranks between the test histograms and 
each of the samples.'''
result = [0]*len (sample_histograms)
for k, s in enumerate (sample_histograms):  # for each image
for i in xrange(10):# for each histogram slot
for j in xrange(4): # for each brightness level
result[k] += abs (s[i][j] - test_histogram[i][j])   
return result


if __name__ == '__main__':
import getopt, sys
opts, args = getopt.getopt (sys.argv[1:], '', [])
if not args:
args = [
'bears1.jpg',
'bears2.jpg',
'bears3.jpg',
'roses1.jpg',
'roses2.jpg',
'ff1.jpg',
'ff2.jpg',
'sky1.jpg',
'sky2.jpg',
'water1.jpg',
'lake1.jpg',
]
test_pic = 'bears2.jpg' 
else:
test_pic, args = args[0], args[1:]

z = [row_column_histograms (a) for a in args]
test_z = row_column_histograms (test_pic)

file_ranks = zip (difference_ranks (test_z, z), args)   
file_ranks.sort()

print '%12s' % (test_pic,)
print ''
for r in file_ranks:
print '%12s %7.2f' % (r[1], r[0] / 3600.0,)



(omitting a few comments that wrapped around.)  The test-case still agrees 
with your archived version:

mwilson@tecumseth:~/sandbox/im_sim$ python image_rank.py bears2.jpg *.jpg
  bears2.jpg

  bears2.jpg0.00
  bears3.jpg   15.37
  bears1.jpg   19.20
sky1.jpg   23.20
sky2.jpg   23.37
 ff1.jpg   25.30
   lake1.jpg   26.38
  water1.jpg   26.98
 ff2.jpg   28.43
  roses1.jpg   32.01


I'd vaguely wanted to do something like this for a while, but I never dug 
far enough into PIL to even get started.  An additional kind of ranking that 
takes colour into account would also be good -- that's the first one I never 
did.

Cheers, Mel.

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


  1   2   3   4   >