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


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: [python 2.4] unable to construct tuple with one item

2007-05-06 Thread Mel Wilson
Vyacheslav Maslov wrote:
 So, the main question is why using syntax like [X] python constuct list 
 with
 one item, but when i try to construct tuple with one item using similar
 syntax (X) python do nothing?

Because `(` and  `)` are used in expressions to bracket sub-expressions.

a = (4 + 3) * 2

means: add 4 to 3, multiply the sum by 2.  It can't mean: make a tuple 
containing 7 and extend it to 7,7 .

The real constructor for tuples is `,`.  When you see parens around 
tuple creation they're there to bracket the sub-expression that 
creates the tuple.  You see new tuples without parens all the time:

for i, thing in enumerate (things): ...

starter, main_course, dessert, beverage = order_meal (*hunger)

etc.


Mel.

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


Re: Numbers and truth values

2007-04-28 Thread Mel Wilson
John Nagle wrote:
  True, False, and None should be reserved words in Python.
 None already is.

The permissiveness makes it less painful to upgrade to new versions of 
Python.  True and False only recently got assigned conventional 
values, but you can still import old modules without worrying whether 
they might violate the new rule; if True and False once meant 
something special to them, it will still mean the same thing.

Meanwhile new code can follow the new conventions.



Mel.

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


Re: When are immutable tuples *essential*? Why can't you just use lists *everywhere* instead?

2007-04-23 Thread Mel Wilson
Neil Cerutti wrote:

 The interpreter explains it: A list is not a hashable object.
 Choosing a hash table instead of some kind of balanced tree seems
 to be just an optimization. ;)

Even with a balanced tree, if a key in a node changes value, you may 
have to re-balance the tree.  Nothing in a Python list says that a 
dictionary tree would have to be re-balanced if you changed that 
particular list.

Mel.

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


Re: List of Objects

2007-04-19 Thread Mel Wilson
[EMAIL PROTECTED] wrote:
 Howdy, a (possibly) quick question for anyone willing to listen.
 I have a question regarding lists and Classes; I have a class called
 gazelle with several attributes (color, position, etc.) and I need
 to create a herd of them. I want to simulate motion of individual
 gazelles, but I don't want to have to go through and manually update
 the position for every gazelle (there could be upwards of 50). I was
 planning to create an array of these gazelle classes, and I was going
 to iterate through it to adjust the position of each gazelle. That's
 how I'd do it in C, anyway. However, Python doesn't support pointers
 and I'm not quite sure how to go about this. Any help you can provide
 would be greatly appreciated.
 Thanks a lot!

You don't want a herd of the Platonic type of gazelle, you want a herd 
of individual instances of the class of gazelle.  No problem.
Something like

class Gazelle(object):
 def __init__ (self, color, position)
 self.color = color
 self.position = position
# ...
herdsize = 30
herd = []
for i in xrange (herdsize)
 color, position = function_to_supply_a_gazelle's_attributes()
 herd.append (Gazelle (color, position)
# ...
while true:
 for gazelle in herd:
 do_something_to (gazelle)

 
 -Ryan
 

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


Re: Python Feature Request: Allow changing base of member indices to 1

2007-04-14 Thread Mel Wilson
jamadagni wrote:
 OK fine. It is clear that this feature must be implemented if at all
 only on a per-module basis. So can we have votes for per-module
 implementation of this feature?

The only way that can work is if the API to the module doesn't expose 
ANY sequence indices.  It would be a great pain to have to remember 
which of the modules you've imported expect base 0 and which expect 
base 1. (There's a Monty Python sketch: a station full of police 
officers who only understand you if you speak 
slowly/quickly/high-pitched/low-pitched/etc. depending on the 
individual officer.)

The scheme could work if the module was carefully programmed to show 
and accept only application-relevant values that nobody would expect 
to have an alternative base -- quantities of things, arbitrary code 
numbers, and the like.

Mel.

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


Re: Python Feature Request: Add the using keyword which works like with in Visual Basic

2007-04-14 Thread Mel Wilson
[EMAIL PROTECTED] wrote:
 In Visual Basic there is the keyword with which allows an object-
 name to be declared as governing the following statements. For
 example:
 
 with quitCommandButton
  .enabled = true
  .default = true
 end with
 
 This is syntactic sugar for:
 
 quitCommandButton.enabled=true
 quitCommandButton.default=true
 
 This can be very useful especially in GUI programming when we have to
 type the same object name in line-after-line. 

q = quitCommandButton
q.enabled = true
q.default = true



Mel.

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


Re: Lists and Tuples and Much More

2007-04-12 Thread Mel Wilson
Scott wrote:
 Now I read somewhere that you could change the list inside that tupple.  But 
 I can't find any documentation that describes HOW to do it.  The only things 
 I CAN find on the subject say, Don't do it because its more trouble than 
 it's worth.  But that doesn't matter to me, because I want to know 
 everything.

Python 2.4.4c1 (#2, Oct 11 2006, 21:51:02)
[GCC 4.1.2 20060928 (prerelease) (Ubuntu 4.1.1-13ubuntu5)] on linux2
Type help, copyright, credits or license for more information.
  aa = (1, 2, [3, 4])
  aa
(1, 2, [3, 4])
  aa[2].append ((True, False))
  aa
(1, 2, [3, 4, (True, False)])
 

Like that.
Mel.

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


Re: tuples, index method, Python's design

2007-04-08 Thread Mel Wilson
7stud wrote:
 On Apr 7, 8:27 am, Carsten Haese [EMAIL PROTECTED] wrote:
 Adding useless features always makes a product worse. What's your use
 case for tuple.index?

 I'll trade you an index method for tuples for the whole complex number
 facility.

Actually, I've found the use cases for list.index to be kind of thin. 
  Long before I think Which one of these items is a 3?, I seem to 
have thought dictionary.

Cheers, Mel.

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


Re: [optparse] Problem with getting an option value

2007-04-06 Thread Mel Wilson
Peter Otten wrote:
 Lucas Malor wrote:
 
 Hello all. I'm trying to do a little script. Simply I want to make a list
 of all options with them default values. If the option is not specified in
 the command line, the script must try to read it in a config.ini file. If
 it's not present also there, it must set the default value.

 The problem is I maked a simple list for this:

 optname = [
   [ delete, False ],
   [ file,   file ],
   [ dir, ],

 But I must check that the option was specified in command line:

 (options, args) = parser.parse_args()
 for opt in optname :
   if not options.opt[0] :
 # read the options from config.ini

 The problem is options is an instance, so options.delete, for example,
 is wrong; I should pass options.delete . How can I do?
 
 Use getattr():
 
 for name, default_value in optname:
 if getattr(options, name) == default_value:
 value = ... # read value from config file
 setattr(options, name, value)
 
 Personally, I would always read the config file, use the values found there
 to set up the parser and avoid such post-proc

But then, if the command-line value == the default_value the program 
will try to get a value from the config file.  If the config file 
overrides the defaults, then the command line can't re-override.

Stuck with this, I usually initialize with None, then after all the 
option sources have been done, set anything that's still None to the 
default.  It's not tidy.

If even None could be a valid value, then a new None:

class LikeNothingElse:
 '''Not a reasonable option value for anything'''
# ... various code
option_a = LikeNothingElse
option_b = LikeNothingElse
# ... process all the option sources
if option_a == LikeNothingElse:
 option_a = None


Mel.

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


Re: Need help on reading line from file into list

2007-04-03 Thread Mel Wilson
bahoo wrote:
[ ... ]
 Thanks, this helped a lot.
 I am now using the suggested
 map(str.strip, open('source.txt').readlines())
 
 However, I am a C programmer, and I have a bit difficulty
 understanding the syntax.
 I don't see where the str came from, so perhaps the output of
 open('source.txt').readlines() is defaulted to str?

You can do without.

[x.strip() for x in open ('source.txt', 'r')]

will also work.

Cheers, Mel.


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


Re: Fortran vs Python - Newbie Question

2007-03-28 Thread Mel Wilson
Terry Reedy wrote:
 Tim Roberts [EMAIL PROTECTED] wrote in message 
 news:[EMAIL PROTECTED]
 | Once upon a time,
 | Basic enthusiasts would have used the word tokenized to describe .pyc 
 files.
 
 Perhaps, but they would, I think, have been wrong.  Tokenized Basic to the 
 best of my knowledge, is a reversibly compressed version of the source 
 file.  The 'while' keyword, is there is one, is replaced by a number, but 
 no parsing is done.

Almost reversibly.  The giveaway was when you listed your BASIC 
program and all the keywords came out upper-case, regardless of what 
case you'd typed them in.

Mel.

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


Re: exit to interpreter?

2007-03-23 Thread Mel Wilson
belinda thom wrote:
 On Mar 23, 2007, at 11:04 AM, [EMAIL PROTECTED] wrote:
 
 On Mar 23, 12:52 pm, belinda thom [EMAIL PROTECTED] wrote:
 Hi,

 I'm writing a function that polls the user for keyboard input,
 looping until it has determined that the user has entered a valid
 string of characters, in which case it returns that string so it can
 be processed up the call stack. My problem is this. I'd also like it
 to handle a special string (e.g. 'quit'), in which case control
 should return to the Python command line as opposed to returning the
 string up the call stack.

 sys.exit seemed like a good choice, but it exits the python  
 interpreter.

 I could use an exception for this purpose, but was wondering if
 there's a better way?

A custom-defined exception is probably the best way to jump out of a 
stack of nested calls.


Mel.

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


Re: How to get the previous line in a file?

2007-03-18 Thread Mel Wilson
Qilong Ren wrote:
 Hi, Shane,
 
 Thanks for fast reply.
 
 What I used is :
for line in open(FILE):
do stuff
 I don't want to store all lines in a list because sometimes the file is very 
 large. We need to store the value of the previous line in a variable. Is that 
 right? 

Almost.  Strictly, we need to bind a name to the object holding the 
previous value, so we can refer to that object later.  :)

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


Re: number generator

2007-03-10 Thread Mel Wilson
Gerard Flanagan wrote:
 On Mar 9, 4:17 pm, cesco [EMAIL PROTECTED] wrote:
 On Mar 9, 3:51 pm, Paul Rubin http://[EMAIL PROTECTED] wrote:

 cesco [EMAIL PROTECTED] writes:
 I have to generate a list of N random numbers (integer) whose sum is
 equal to M. If, for example, I have to generate 5 random numbers whose
 sum is 50 a possible solution could be [3, 11, 7, 22, 7]. 
 
 Suppose you have a fixed telegraph pole at N and a fixed telgraph pole
 at M, and you're given 5 more telegraph poles...
 
That's a good one!  Three-liner.

Cheers, Mel.

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


Re: carshing the interpreter in two lines

2006-06-04 Thread Mel Wilson
sam wrote:
 Mel:
 Wow that book brings back memories. I scanned my copy to review the
 subject covered, and came to the conclusion that mind reading
 algorithms are the answer.
 
I gathered from somewhere (but not the index to Andrew 
Hodges' biography) that Turing was toying with an idea for 
oracles, where a computation would be allowed to call out 
sometimes to a non-computational process to obtain some 
required result.  Used maybe by  interactive debugging programs.

 Cheers,Mel.

 Mel Wilson wrote:
[ ... ]
Douglas Hofstadter's _Goedel, Escher, Bach: an Eternal Golden Braid_.
[ ... ]
 Contracrostipunctus.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Proposed new PEP: print to expand generators

2006-06-04 Thread Mel Wilson
Terry Reedy wrote:
 James J. Besemer [EMAIL PROTECTED] wrote in message 
 news:[EMAIL PROTECTED]
 I propose that we extend the semantics of print such that if the object 
 to
 be printed is a generator then print would iterate over the resulting
 sequence of sub-objects and recursively print each of the items in order.
 Iterating over an iterator is usually destructive.  So you would be 
 printing what it was but no longer is.  This is why iterators are printed 
 differently from sequences.

I guess the motivation is the case of people who would set 
up an iterator specifically to print from it.

print-as-debug-aid would get badly broken by the proposal, 
and I'd find that painful.

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


Re: carshing the interpreter in two lines

2006-06-03 Thread Mel Wilson
sam wrote:
 tomer:
 
 It is my opinion that you would loose performance if the Python
 interpreter had the additional task of verifying byte code. It might be
 more appropriate to have a preprocessor that did the verifying as it
 compiled the byte code.

Possibly.  A good book on the topic is Douglas Hofstadter's 
_Goedel, Escher, Bach: an Eternal Golden Braid_.

Particularly starting from the chapter Contracrostipunctus.

 Cheers,Mel.



 Sam Schulenburg
 
 gangesmaster wrote:
 the following (random) code crashes my interpreter
 (python 2.4.3/winxp):

 from types import CodeType as code
 exec code(0, 5, 8, 0, hello moshe, (), (), (), , , 0, )

 i would expect the interpreter to do some verifying, at least for
 sanity (valid opcodes, correct stack size, etc.) before executing
 artbitrary code... after all, it was the BDFL who said I'm not
 saying it's uncrashable. I'm saying that if you crash it, it's a
 bug unless proven harebrained.


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


Re: using import * with GUIs?

2006-05-31 Thread Mel Wilson
John Salerno wrote:
 Hi all. Quick question (but aren't they all?) :)
 
 Do you think it's a good idea to use the 'from name import *' 
 statement when using a GUI module? It seems on wxPython's site, they 
 recommend using import wx nowadays, but I wonder if that advice is 
 followed. Also, I'm still reading some Tkinter docs that seem to use 
 'from Tkinter import *' a lot.
 
 I understand the danger of doing this, but is it safer in these cases, 
 given the more specific names that GUI frameworks tend to use 
 (sometimes!)? Or should you still qualify all your calls with the module?
More specific?  I dunno, I have trouble thinking of that
huge multitude of names in wx as specific.  Who knows what
in all that might collide with names you devise?

My formative experience came when I was looking at Python
Imaging Library Demo code.  Somebody did a simple call to
open and got returned an entire Jpeg image object.  I knew
that open was destined to take arguments other than simple
file paths, and return things other than simple files, but
it seemed awfully soon.  Then I got suspicious, looked at
the top of the code, and saw from Image import *

So a word, too, to people writing demo programs.  Writing
from mycode import * obscures which code is actually yours
in the code following.  Kind of defeats the purpose.

 Cheers,Mel.

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


Re: list comprehensions put non-names into namespaces!

2006-05-26 Thread Mel Wilson
[EMAIL PROTECTED] wrote:
 Lonnie List comprehensions appear to store their temporary result in a
 Lonnie variable named _[1] (or presumably _[2], _[3] etc for
 Lonnie nested comprehensions)
 
 Known issue.  Fixed in generator comprehensions.  Dunno about plans to fix
 it in list comprehensions.  I believe at some point in the future they may
 just go away or become syntactic sugar for a gen comp wrapped in a list()
 call.

Point of information, would this be the interpreter putting
the result of its last calculation in _ ?

Python 2.4.2 (#1, Jan 23 2006, 21:24:54)
[GCC 3.3.4] on linux2
Type help, copyright, credits or license for more 
information.
  [2*x for x in range(5)]
[0, 2, 4, 6, 8]
  _[4]
8



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


Re: genexp surprise (wart?)

2006-05-26 Thread Mel Wilson
Paul Rubin wrote:
 Paul Du Bois [EMAIL PROTECTED] writes:
 The second is that you don't like the late-binding behavior of
 generator expressions. PEP 289 has this to say:

 After much discussion, it was decided that the first (outermost)
 for-expression should be evaluated immediately and that the remaining
 expressions be evaluated when the generator is executed.
 
 Thanks.  That PEP is informative.  It shows that I stumbled into
 something that other people found confusing too, and that alternatives
 were considered that turned out not to be better.

The net effect of the bad version seems to be that you're
not getting a new generator from
 stream = (q for q in stream if q%p != 0)
(* disassembly shown below.)

Disassembly seems to show the program getting a pre-compiled
generator expression code block, and binding the new value
of p to it, then getting iter(stream), which is stream.  As
Paul Du Bois says, the outer loop is fixed, but the
subsequent if-expression is liable to change.

So 3 passes because 3%2 != 0
4 passes because 4%3 != 0
5 passes because 5%4 != 0
and so on.


 Interesting.

* Disassembly of stream = ...:

   6  47 LOAD_CLOSURE 0 (p)
  50 LOAD_CONST   2 (code object 
generator expression at 009D65E0, file try_eratos.py, 
line 6)
  53 MAKE_CLOSURE 0
  56 LOAD_FAST1 (stream)
  59 GET_ITER
  60 CALL_FUNCTION1
  63 STORE_FAST   1 (stream)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Learning Python 2nd ed. p479 error?

2006-05-26 Thread Mel Wilson
[EMAIL PROTECTED] wrote:
 Hello all.
 
 On page 479, the 2nd edition of the Learning Python book, this code
 appears
 
 class Derived(Base):
 def __init__(self, arg, *args, **kw):
 self.__init__(self, *args, **kw)
 
 Surely self.__init__ should be
 
 Base.__init__
 
 Everything else in the book has been crystal clear.  Up to page 479!
 It doesn't appear in the errata.  What am I misunderstanding?

Seems to be a typo:

Python 2.4.2 (#1, Jan 23 2006, 21:24:54)
[GCC 3.3.4] on linux2
Type help, copyright, credits or license for more 
information.
  class A(object):
...   def __init__ (self):
... print 'Constructing A'
...
  class B(A):
...   def __init__ (self):
... self.__init__ (self)
...
  B()
Traceback (most recent call last):
   File stdin, line 1, in ?
   File stdin, line 3, in __init__
TypeError: __init__() takes exactly 1 argument (2 given)
  class C(A):
...   def __init__ (self):
... A.__init__ (self)
...
  C()
Constructing A
__main__.C object at 0x402cf5ac




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


Re: how to clear up a List in python?

2006-05-26 Thread Mel Wilson
[EMAIL PROTECTED] wrote:
 The original post only mentions deleting the values in the list, not
 the list itself.  Given that you want to keep the list and just ditch
 the values it contains I'd go with:
 
 list1 = []

Depends what you mean by keep the list.  Consider

class C (object):
 def __init__ (self, things):
 self.things = things

a = range (5)
b = C (a)
a = []
print b.things

d = range (5)
e = C (d)
d[:] = []
print e.things



These are very different.
 Mel.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Thinking like CS problem I can't solve

2006-05-23 Thread Mel Wilson
Alex Pavluck wrote:
 Hello.  On page 124 of Thinking like a Computer Scientist.  There is
 an exercise to take the following code and with the use of TRY: /
 EXCEPT: handle the error.  Can somone help me out?  Here is the code:
 [ ... ]

What error?

Python 2.4.2 (#1, Jan 23 2006, 21:24:54)
[GCC 3.3.4] on linux2
Type help, copyright, credits or license for more 
information.
  def inputNumber(n):
... if n == 17:
... raise 'BadNumberError: ', '17 is off limits.'
... else:
... print n, 'is a nice number'
... return n
...
  inputNumber(17)
Traceback (most recent call last):
   File stdin, line 1, in ?
   File stdin, line 3, in inputNumber
BadNumberError: : 17 is off limits.


That error, I guess.  try:/except...: can catch it and 
prevent the traceback.  You could, say, print your own 
message and continue with your script.  Look up how to
use try:/except... .

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


Re: Question about exausted iterators

2006-05-19 Thread Mel Wilson
[EMAIL PROTECTED] wrote:
 Consider this example:
 
 X = range(5)
 Y = iter(X)
 Z = iter(Y)
 
 As you can see, X is a container, and Y is an iterator.
 They are simliar in that iter works on them both.
 
 Cristoph claims that this causes confusion.
 Why? Because iter doesn't have the same meaning for both of them.
 For X it always returns an iterator that yields the same set of values.
 For Y it returns an iterator yielding different values each time.

As an aside, perhaps iter(Y) should be returning a deeper 
copy of Y.  As it stands, I see 'Z=Y' giving the same effect:

  y=iter(x)
  z=iter(y)
  zip(y, z)
[(0, 1), (2, 3)]
  y=iter(x)
  z=y
  zip(y, z)
[(0, 1), (2, 3)]

[ ... ]

 But changing iter to have the same meaning for containers and
 iterables is impossible.
 You cannot, conceptually, reiterate an iterator.
 So what Cristoph is suggesting - is to add an exception for the cases
 in which iterators and collections behave differently.
 Somewhat similar to this:

But the end, raising StopIteration is not where the 
difference is.  The difference is in iter(some_object).

iter(some_container) creates a brand new iterator, standing 
at the starting line and ready to run.

iter(some_listiterator), it seems, just returns a reference 
to some_listiterator, with some of its history possibly 
behind it.

Iterators are used in the same syntactic places as general 
iterables, but especially once people start giving them 
names and handing them around, the real differences show up.

The short-range solution is Know What You're Doing.  Duck 
typing is a fine thing, but it works best for programmers 
who keep scrupulous track of their objects' types.

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


Re: [silly] Does the python mascot have a name ?

2006-05-19 Thread Mel Wilson
John D Salt wrote:
 Mel Wilson [EMAIL PROTECTED] wrote in news:_s2bg.8867$aa4.296233
 @news20.bellglobal.com:
 
 [Snips]
 Just reinforces the central truth.  The mascot doesn't 
 *have* a name.  Most things don't. 
 
 Most things don't have names?
 
 I'll believe you if you can give me a list of ten things that don't have 
 names.
 
 ;-)

!!!

[object() for i in xrange(10)]


 
 All the best,
 
 John.  

Likewise,

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


Re: Complex evaluation bug

2006-05-18 Thread Mel Wilson
of wrote:
 a = 1+3j
 complex(str(a))
 
 Why does this not work ? It should

It would be nice.
Looks like str(1+3j) is returning an expression in string 
form.  Maybe there is no actual complex literal.

eval (str(1+3j)) works.

Python 2.4.2 (#1, Jan 23 2006, 21:24:54) [GCC 3.3.4] on linux2
Type help, copyright, credits or license for more 
information.
  1+3j
(1+3j)
  str(1+3j)
'(1+3j)'
  complex (str(1+3j))
Traceback (most recent call last):
   File stdin, line 1, in ?
ValueError: complex() arg is a malformed string
  eval (str(1+3j))
(1+3j)
  eval(str(1+3j))**2
(-8+6j)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [silly] Does the python mascot have a name ?

2006-05-18 Thread Mel Wilson
Steve wrote:
 Carl J. Van Arsdall wrote:
 John D Salt wrote:
 hon-list/2003-September/185612.html
 Odi must be the Dutch for Monty.
 Nope. If it was Dutch it would probably be Odie
 Damn.
   
 Odi(e) was a punk.  I'm gonna be a rebel without a cause and stay with 
 Monty ;)
 Yes ! Monty sounds much better ! ...also imagine the expression on the 
 PHB's face if this were to happen ...

Just reinforces the central truth.  The mascot doesn't 
*have* a name.  Most things don't.  You're welcome to assign 
it the name Monty if you want.

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


Re: printing list

2006-05-07 Thread Mel Wilson
Tim Chase wrote:
 compboy wrote:
 
 How do you print elements of the list in one line?

 alist = [1, 2, 5, 10, 15]

 so it will be like this:
 1, 2, 5, 10, 15
 
 
   print ', '.join(alist)
 1, 2, 5, 10, 15

???

Python 2.4.2 (#1, Jan 23 2006, 21:24:54)
[GCC 3.3.4] on linux2
Type help, copyright, credits or license for more 
information.
  a=[1,2,3,4,5]
  print ', '.join (a)
Traceback (most recent call last):
   File stdin, line 1, in ?
TypeError: sequence item 0: expected string, int found
  print ', '.join ('%d'%x for x in a)
1, 2, 3, 4, 5
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tuple assignment and generators?

2006-05-05 Thread Mel Wilson
vdrab wrote:
 I guess the take-away lesson is to steer clear from any reliance on
 object identity checks, if at all possible.  Are there any other such
 optimizations one should like to know about?

Object identity checks are just the thing/numero uno/ichiban 
for checking object identity.  A code snipped like

 def broadcast (self, message):
 Broadcast a message to all the other game players.
 for p in all_players:
 if p is not self:
 p.send (message)

does just what I want and expect it to.

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


Re: simultaneous assignment

2006-05-02 Thread Mel Wilson
Roger Miller wrote:
 Steve R. Hastings wrote:
 
 
a = 0
b = 0
a is b  # always true
 
 
 Is this guaranteed by the Python specification, or is it an artifact of
 the current implementation? 

AFAIK it's an artifact.  The performance hit it Python 
stopped sharing small integers could be enormous, 
nonetheless sharing isn't part of the specification
My understanding has been that an
 implementation is free to share integer objects or not, so using 'is'
 as an equality test takes you into undefined territory, regardless  of
 the size of the value.
 
I agree.  is is for working with linked-lists or trees, or 
other applications where object identity is really and truly 
what you're interested in.

Some amusing is/== facts, some suggested by recent threads

Python 2.4.2 (#1, Jan 23 2006, 21:24:54)
[GCC 3.3.4] on linux2
Type help, copyright, credits or license for more 
information.
  0 is 0.0
False
  -0.0 is 0.0
False
  0 == 0.0 == -0.0
True
  100 is (200/2)
False
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: lambda

2006-04-21 Thread Mel Wilson
[EMAIL PROTECTED] wrote:
 Hello,
 
 I need your help understanding lambda (and doing it a better way
 without).
 
 f  = lambda x : x*x
[ ... ]
 # the idea is now to give the definition of the multiplication of
 functions and integers
 # (f * c)(xx) := f(x)*c
 [lambda xx: f(xx)*y for y in range(1,5)][0](1)
 # returns 4
 # I would expect 1*x*x = 1

I think you have to get the value of y at definition time, 
not at call time:

  z=[lambda xx, yy=y: (f(xx)*yy) for y in xrange(1,5)]
  z[0](1)
1

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


Re: Generate a sequence of random numbers that sum up to 1?

2006-04-21 Thread Mel Wilson
Anthony Liu wrote:
 I am at my wit's end.
 
 I want to generate a certain number of random numbers.
  This is easy, I can repeatedly do uniform(0, 1) for
 example.
 
 But, I want the random numbers just generated sum up
 to 1 . 
 
 I am not sure how to do this.  Any idea?  Thanks.

numbers.append (random.uniform (0, 1.0-sum(numbers)))

might help, perhaps.

or

scaled = [x/sum(numbers) for x in numbers]

 Mel.

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


Re: list.clear() missing?!?

2006-04-13 Thread Mel Wilson
Alan Morgan wrote:
 In article [EMAIL PROTECTED],
 Raymond Hettinger [EMAIL PROTECTED] wrote:
* s.clear() is more obvious in intent
 
 Serious question: Should it work more like s=[] or more like
 s[:]=[].  I'm assuming the latter, but the fact that there is
 a difference is an argument for not hiding this operation behind
 some syntactic sugar. 


It has to work more like s[:]=[]

It's not easy for an object method to bind a whole different 
object to the first object's name.  Generally only 
statements can affect namespaces (hence the uses of del that
everyone remembers.)

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


Re: list.clear() missing?!?

2006-04-13 Thread Mel Wilson
Steven D'Aprano wrote:
 Convenience and obviousness are important for APIs -- that's why lists
 have pop, extend and remove methods. The only difference I can see between
 a hypothetical clear and these is that clear can be replaced with a
 one-liner, while the others need at least two, e.g. for extend:
 
 for item in seq: 
 L.append(item)

Both extend and append have one-line slice equivalents,
except that the equivalents have to keep referring to
the length of the list.. (have to keep finding the
len function.)

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


Re: list.clear() missing?!?

2006-04-12 Thread Mel Wilson
Ville Vainio wrote:
 Fredrik Lundh wrote:
because Python already has a perfectly valid way to clear a list,
perhaps ?

del l[:]
 
 
 Ok. That's pretty non-obvious but now that I've seen it I'll probably
 remember it. I did a stupid while l: l.pop() loop myself.

Actually, it's in the Library Reference (that we keep under 
our pillows) section 2.3.6.4 Mutable Sequence Types.

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


Re: inserting into a list

2006-03-07 Thread Mel Wilson
John Salerno wrote:
 Christoph Haas wrote:
 L[2:2]=[3]
[ ... ]
  What if you wanted to insert an actual list into that 
slot? Would
 you have to wrap it in double brackets?

Yep.

It's a strong-typing thing.  Slices of lists are lists, and 
therefore what you assign to one has got to be a list, or 
convertible to a list (a tuple would work.)

Python 2.4.2 (#1, Jan 23 2006, 21:24:54)
[GCC 3.3.4] on linux2
Type help, copyright, credits or license for more 
information.
  a=[1,3,4]
  a[2:3]
[4]
  a[2:2]
[]
  a[1:1]=[2]
  a
[1, 2, 3, 4]
  a[1:2]
[2]


 Mel.

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


Re: type = instance instead of dict

2006-02-28 Thread Mel Wilson
James Stroud wrote:
 Fredrik Lundh wrote:
 
 James Stroud wrote:


 Perhaps you did not know that you can inheret directly from dict, which
 is the same as {}. For instance:

 class Dict({}):
   pass
 
 
 I must have been hallucinating. I swear I did this before and it worked 
 just like class Dict(dict). Since it doesn't read as well, I've never 
 used it.
 


class D (type({})):
 '''This derivative of dictionary works.'''

Could that have been it?

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


Re: Question about idioms for clearing a list

2006-02-06 Thread Mel Wilson
Fredrik Lundh wrote:

 (del doesn't work on dictionaries)

... or rather [:] doesn't work on dictionaries ...

Python 2.4.2 (#1, Jan 23 2006, 21:24:54)
[GCC 3.3.4] on linux2
Type help, copyright, credits or license for more information.
  d={'a':1, 'b':2, 'c':3}
  print d
{'a': 1, 'c': 3, 'b': 2}
  del d['b']
  print d
{'a': 1, 'c': 3}
  del d[:]
Traceback (most recent call last):
   File stdin, line 1, in ?
TypeError: unhashable type
 

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


Re: how to improve this simple block of code

2006-01-11 Thread Mel Wilson
py wrote:
 Say I have...
 x = 132.00
 
 but I'd like to display it to be 132 ...dropping the trailing
 zeros...

print '%g' % (float(x),)

might work.

Mel.

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


Re: Suggestion for syntax error: ++i, --i

2004-12-13 Thread Mel Wilson
In article [EMAIL PROTECTED],
Christian Ergh [EMAIL PROTECTED] wrote:
Ah, ok, i misunderstood you. Well, to mark it as a syntax error sounds
good, and at the Moment I would not know a case where this conflicts
with a implementation.

   Well, you can overload prefix `+` and `-` operators on an
object by defining __pos__ and __neg__ methods, so --a, ++a,
+-a, -+a, +-+a and other similar combinations are actually
good syntax, and as useful as you want them to be.

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


Re: newbie questions

2004-12-11 Thread Mel Wilson
In article [EMAIL PROTECTED],
houbahop d.lapasset[Remove me)@chello.fr wrote:
Thank you everyone, but I still not understand why such a comon feature like
passing parameters byref that is present in most serious programming
languages is not possible in a clean way,here in python.

I have the habit to never use globals as far as possible and this involve
that my main function is passing some parameters by reference to subs to
allow them to modify the vars.

I would be sad to break my structured programming scheme because a lack of
feature.

In others languages you can use things like pointers to strings or
Mysub(byref MyVar) 

and it does the trick :)

   It isn't a problem with passing by reference.  The
passing-by-reference part works just fine.  Putting in a
print statement to trace what's actually happening:


Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on win32
Type help, copyright, credits or license for more information.
 a = [1,2,3,4,5]
 def X(s):
... for i in xrange (len (s)):
... del s[i]
... print 'X:', s
...
 X(a)
X: [2, 3, 4, 5]
X: [2, 4, 5]
X: [2, 4]
Traceback (most recent call last):
  File stdin, line 1, in ?
  File stdin, line 3, in X
IndexError: list assignment index out of range
 a
[2, 4]



   As the last line shows, lots of things got removed from
`a` .. but not everything.  Roel Schroeven explained why.

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


Re: exec'ing functions

2004-12-10 Thread Mel Wilson
In article [EMAIL PROTECTED],
Peter Otten [EMAIL PROTECTED] wrote:
Mel Wilson wrote:
 The thing is, that once you drop local-namespace
 optimization, the entire function gets slowed down, possibly
 by 40%:
It's not that bad as most of the extra time is spend on compiling the
string.
[ ... ]
def fib7(n, c=compile(a, b, i = 0, 1, n, nofile, exec)):
exec c
[ ... ]

!


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


Re: exec'ing functions

2004-12-09 Thread Mel Wilson
In article [EMAIL PROTECTED],
Steven Bethard [EMAIL PROTECTED] wrote:
Jeff Shannon wrote:
 I was referring to functions which have an internal exec statement, not
 functions which are created entirely within an exec -- i.e., something
 like this:

Thanks for the clarification.  Here's the results for some functions
with internal exec statements:

  cat fib.py
def fib1(n):
 a, b = 0, 1
 while True:
 a, b = b, a + b
 yield a


exec \
def fib2(n):
 a, b = 0, 1
 while True:
 a, b = b, a + b
 yield a


def fib3(n):
 a, b = 0, 1
 while True:
 exec a, b = b, a + b
 yield a

def fib4(n):
 exec a, b = 0, 1
 while True:
 exec a, b = b, a + b
 yield a

 
  python -m timeit -s import fib fib.fib1(100)
100 loops, best of 3: 0.71 usec per loop

  python -m timeit -s import fib fib.fib2(100)
100 loops, best of 3: 0.678 usec per loop

  python -m timeit -s import fib fib.fib3(100)
100 loops, best of 3: 0.826 usec per loop

  python -m timeit -s import fib fib.fib4(100)
100 loops, best of 3: 0.821 usec per loop

I'm not sure I'd say they're *much* slower, but you're right; they're
definitely slower.

   The thing is, that once you drop local-namespace
optimization, the entire function gets slowed down, possibly
by 40%:



def fib5 (n):
a, b, i = 0, 1, n
while i  0:
a, b = b, a+b
yield a
i -= 1


def fib6 (n):
exec a, b, i = 0, 1, n
while i  0:
a, b = b, a+b
yield a
i -= 1



f:\home\mwilson\projects\pythonpython  e:\bin\python23\lib\timeit.py -s import
 fib [i for i in fib.fib5(100)]
1000 loops, best of 3: 1.95e+003 usec per loop

f:\home\mwilson\projects\pythonpython  e:\bin\python23\lib\timeit.py -s import
 fib [i for i in fib.fib6(100)]
100 loops, best of 3: 2.82e+003 usec per loop


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


Re: assymetry between a == b and a.__eq__(b)

2004-12-03 Thread Mel Wilson
In article [EMAIL PROTECTED],
Steven Bethard [EMAIL PROTECTED] wrote:
I believe what Peter Otten was pointing out is that calling __eq__ is
not the same as using ==, presumably because the code for == checks the
types of the two objects and returns False if they're different before
the __eq__ code ever gets called.

Doesn't seem to:



Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on win32
Type help, copyright, credits or license for more information.
 class EQ(object):
... def __eq__ (self, other):
... return True
...
 eq = EQ()
 eq == 3
True
 3 == eq
True
 class NEQ(object):
... def __eq__ (self, other):
... return False
...
 neq=NEQ()
 eq == neq
True
 neq == eq
False




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