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

2011-12-24 Thread Steven D'Aprano
On Sat, 24 Dec 2011 09:50:04 +1100, Chris Angelico wrote:

> On Sat, Dec 24, 2011 at 9:32 AM, Steven D'Aprano
>  wrote:
>> Yes. But having to manage it *by hand* is still unclean:
> 
> Well, my point was that Python's current behaviour _is_ that.

Minus the managing it by hand part.


>> * you still have to assign the default value to the function assignment
>> outside the function, which is inelegant;
> 
> C's static variables are initialized inside the function. But since
> Python doesn't have that, it doesn't really work that way. (You might be
> able to use a decorator to do some cool tricks though.)

If Python were C, then static variables would be the right solution, but 
since it isn't, they aren't.



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


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

2011-12-24 Thread Steven D'Aprano
On Fri, 23 Dec 2011 19:24:44 -0500, Devin Jeanpierre wrote:

>> To fake early binding when the language provides late binding, you
>> still use a sentinel value, but the initialization code creating the
>> default value is outside the body of the function, usually in a global
>> variable:
>>
>>_DEFAULT_Y = []  # Private constant, don't touch.
>>
>>def func(x, y=None):
>>if y is None:
>>y = _DEFAULT_Y
>>...
>>
>> This separates parts of the code that should be together, and relies on
>> a global, with all the disadvantages that implies.
> 
> No, you can just do def func(x, y=_DEFAULT_Y): ...

Point taken. Nevertheless, the semantics are still not the same as actual 
early binding: if the global name is deleted or changed, the function 
stops working.



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


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

2011-12-24 Thread Steven D'Aprano
On Fri, 23 Dec 2011 17:03:11 +, Neil Cerutti wrote:

>> The disadvantage of late binding is that since the expression is live,
>> it needs to be calculated each time, even if it turns out to be the
>> same result. But there's no guarantee that it will return the same
>> result each time:
> 
> That's its main *advantage*.

Ah yes, sorry, poor wording on my part. Whether calculating the default 
value *once* or *each time* is an advantage or disadvantage depends on 
what you're trying to do. Either way, it could be just what you want, or 
an annoying source of bugs.


>> consider a default value like x=time.time(), which will return a
>> different value each time it is called; or one like x=a+b, which will
>> vary if either a or b are changed. Or will fail altogether if either a
>> or b are deleted. This will surprise some people some of the time and
>> lead to demands that Python "fix" the "obviously buggy" default
>> argument gotcha.
> 
> It's hard to see anyone being confused by the resultant exception.

That's because you're coming at it from the perspective of somebody who 
knows what to expect, in the middle of a discussion about the semantics 
of late binding. Now imagine you're a newbie who has never thought about 
the details of when the default value is created, but has a function like 
"def foo(x, y=a+b)". He calls foo(x) seven times and it works, and on the 
eighth time it blows up, perhaps with a NameError. It's surprising 
behaviour, and newbies aren't good at diagnosing surprising bugs.

Or worse, it doesn't blow up at all, but gives some invalid value that 
causes your calculations to be completely wrong. Exceptions are not the 
worst bug to have -- they are the best.


> It's
> much harder to figure out what's going wrong with an early-bound
> mutable.

Only for those who don't understand, or aren't thinking about, Python's 
object model. The behaviour of early-bound mutables is obvious and clear 
once you think about it, but it does require you to think about what's 
going on under the hood, so to speak.

[...]
>> To fake early binding when the language provides late binding, you
>> still use a sentinel value, but the initialization code creating the
>> default value is outside the body of the function, usually in a global
>> variable:
[...]
 
> I'd use a function attribute.
> 
> def func(x, y=None):
>   if y is None:
> y = func.default_y
>   ...
> func.default_y = []
> 
> That's awkward only if you believe function attributes are awkward.

I do. All you've done is move the default from *before* the function is 
defined to *after* the function is defined, instead of keeping it in the 
function definition. It's still separate, and if the function is renamed 
your code stops working. In other words, it violates encapsulation of the 
function.

That's not to say that you shouldn't do this. It's a perfectly reasonable 
technique, and I've used it myself, but it's not as elegant as the 
current Python default argument behaviour.


[...]
> The greater efficiency was probably what decided this question for
> Python, right? Since late-binding is so easy to fake, is hardly ever
> what you want, and would make all code slower, why do it?

Excellent point.


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


Re: what does 'a=b=c=[]' do

2011-12-24 Thread Lie Ryan

On 12/22/2011 10:20 AM, Dennis Lee Bieber wrote:


which is to define the names "a", "b", and "c", and connects the three
names to the single object (integer 7 or new empty list).


note that this "connects" and "disconnecting" business is more commonly 
referred to in python parlance as "binding" a name to an object.


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


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

2011-12-24 Thread alex23
On Dec 24, 2:27 am, Mel Wilson  wrote:
> 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.

What on earth gave you the impression Python was bleeding edge? As
there's more to the language than its syntax, "breaking workflow"
disrupts the core library as much as it does the code of everyone
else.

More importantly, you're talking pap. Research is as much about
communication as programming; if you expect every single researcher in
a discipline (or even in the same _building_) to remain in perfect
lockstep with the version releases of a domain-relevant language,
you're either not a researcher or not a very good one. You should get
out to a conference occasionally and see what people think about your
"concept of the week" idea.
-- 
http://mail.python.org/mailman/listinfo/python-list


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

2011-12-24 Thread alex23
On Dec 24, 2:15 am, Roy Smith  wrote:
> I know this is not quite the same thing, but it's interesting to look at
> what django (and mongoengine) do in their model definitions, prompted by
> your time.time() example.  You can do declare a model field something
> like:
>
> class Foo(models.Model):
>    timestamp = DateTimeField(default=datetime.utcnow)
>
> Now, when you create a Foo, if you don't supply a timestamp, it
> generates one by calling utcnow() for you.  Very handy.
>
> I'm not arguing that Python should do that, just pointing out an example
> of where late binding is nice.

There is absolutely nothing stopping you from writing functions now
with that behaviour. All Python functions are "early binding, late
calling" with their arguments, if you treat the arguments as callables
within the function body.



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


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

2011-12-24 Thread alex23
On Dec 24, 6:25 pm, Steven D'Aprano  wrote:
> > It's
> > much harder to figure out what's going wrong with an early-bound
> > mutable.
>
> Only for those who don't understand, or aren't thinking about, Python's
> object model. The behaviour of early-bound mutables is obvious and clear
> once you think about it, but it does require you to think about what's
> going on under the hood, so to speak.

And here we've come full circle to the point of this thread.

If Python was ever 'fixed' to prevent this issue, I'm pretty sure we'd
see an increase in the number of questions like the OP's.
-- 
http://mail.python.org/mailman/listinfo/python-list


[ANN] pyspread 0.2.0

2011-12-24 Thread Martin Manns

==
pyspread 0.2.0
==


Pyspread 0.2.0 has been released.

The new version is an almost complete rewrite for better stability and
maintainability.


About pyspread
==

Pyspread is a non-traditional spreadsheet application that is based on
and written in Python. Pyspread expects Python expressions in its grid
cells, which makes a spreadsheet specific language obsolete.

Pyspread is free software. It is released under the GPL v3.

The project website has changed to http://manns.github.com/pyspread/


What's new in 0.2.0
===

 + Windows support discontinued

 + New pys save file format

 + A lot of bug fixes and small changes to the user interface


Enjoy

Martin


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


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

2011-12-24 Thread Eelco
On Dec 20, 4:30 am, alex23  wrote:
> On Dec 19, 8:15 pm, Eelco  wrote:
>
> > What does that have to do with collection packing/unpacking?
>
> It's mocking your insistance that collection unpacking is a type
> constraint.

This is really going to be the last time I waste any words on this:

The sentence 'collection unpacking is a type constraint' is entirely
nonsensical. A type constraint is a linguistical construct that can be
applied in many ways; typically, to narrow down the semantics of use
of the symbol to which the type constraint is applied.

In case of python, collection PACKING (not unpacking) is signaled by a
construct that can be viewed as a type constraint. But if you dont
want to fortify your view of the syntax by looking at what it is
actually going on, ill repeat again; lets keep things simple, and not
analyze it in detail.

So here it is again, in terms every 5 year old can understand. Id like
to do the exact same thing python is already doing. Except with a few
more, and different symbols, to enable one to express a few different
variants of behavior. Clear enough?
-- 
http://mail.python.org/mailman/listinfo/python-list


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

2011-12-24 Thread Eelco
On Dec 21, 4:48 pm, Neal Becker  wrote:
> Clarification: where can packing/unpacking syntax be used?
>
> It would be great if it were valid essentially anywhere (not limited to
> parameter passing).
>
> What about constructs like:
>
> a, @tuple tail, b = sequence?

This has come up many times in the thread, including in my OP. More
closely unifying collection packing/unpacking is part of my goal, so
indeed, I would like to be able to write something like:

a, middle::tuple, b = ::sequence

Where I would like the extra :: before the sequence to explicitly
signal collection unpacking on the rhs, to maintain the symmetry with
collection unpacking within a function call.
-- 
http://mail.python.org/mailman/listinfo/python-list


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

2011-12-24 Thread Eelco
On Dec 20, 4:35 am, alex23  wrote:
> Eelco  wrote:
> > Having two seperate symbols seperated by whitespace, as in @list args
> > strikes me as a terrible break of normal python lexical rules.
>
> You mean like 'is not'? And the upcoming 'yield from'?

Im not sure why, but this feels like something entirely different to
me.

I suppose because these are compositions of keywords. Can you give an
example of a whitespaced composition of identifiers being a valid
construct anywhere else in Python?
-- 
http://mail.python.org/mailman/listinfo/python-list


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

2011-12-24 Thread Eelco
On Dec 20, 6:47 am, Steven D'Aprano  wrote:
> On Mon, 19 Dec 2011 19:35:20 -0800, alex23 wrote:
> > Eelco  wrote:
> >> Having two seperate symbols seperated by whitespace, as in @list args
> >> strikes me as a terrible break of normal python lexical rules.
>
> > You mean like 'is not'? And the upcoming 'yield from'?
>
> Also "not in".
>
> Space-delimited tokens are hardly rare in Python, e.g.:
>
> import module as name
> for x in sequence
> if flag
> elif condition
> while condition
> with obj
> del name
>
> Nevertheless, I think the suggested syntax "@list args" is awful.
>
> --
> Steven

Can you give an example of a construct in python where two whitespace
delimited identifiers are legal?
-- 
http://mail.python.org/mailman/listinfo/python-list


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

2011-12-24 Thread Eelco
On Dec 22, 2:12 pm, Steven D'Aprano  wrote:
> On Thu, 22 Dec 2011 06:49:16 -0500, Neal Becker wrote:
> > I agree with the OP that the current syntax is confusing.  The issue is,
> > the meaning of * is context-dependent.
>
> Here you are complaining about an operator being "confusing" because it
> is context-dependent, in a post where you strip all context except the
> subject line and expect us to still understand what you're talking about.
> There's a lesson there, I'm sure.
>
> * is context dependent. You know what else is context dependent? Well,
> most things. But in particular, parentheses. Clearly they must be
> "confusing" too. So how about we say:
>
> class MyClass superclasslist A, B C:
>     def method argumentlist self, x, y:
>         t = tuple 1, 2 tuple 3, 4 endtuple endtuple
>         return group x + y endgroup * group x - y endgroup
>
> Much less confusing!
>
> --
> Steven

Context dependence is not something to be avoided at all costs, but
all else being equal, less is certainly more. The general concept of
grouping thing together which parenthesis is an extremely pervasive
one in programming, and thus deserves its own set of context-dependent
rules. Packing and unpacking collections is far, far more rare, and
thus a form that requires you to write more but remember less is
certainly relatively favorable.
-- 
http://mail.python.org/mailman/listinfo/python-list


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

2011-12-24 Thread Chris Angelico
On Sun, Dec 25, 2011 at 1:47 AM, Eelco  wrote:
> a, middle::tuple, b = ::sequence

Then it ought to be

::(a, middle::tuple, b) = ::sequence

or something, because you're doing the same thing on both sides.

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


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

2011-12-24 Thread Chris Angelico
On Sun, Dec 25, 2011 at 1:45 AM, Eelco  wrote:
> Can you give an example of a construct in python where two whitespace
> delimited identifiers are legal?

What do you mean? Two identifiers, separated only by whitespace and no
keyword or operator?

def foo():
asdf
qwer

Perfectly legal, two statements that probably don't do anything useful though.

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


How to check for single character change in a string?

2011-12-24 Thread tinnews
Can anyone suggest a simple/easy way to count how many characters have
changed in a string?

E.g. giving results as follows:-

abcdefg abcdefh 1
abcdefg abcdekk 2
abcdefg gfedcba 6


Note that position is significant, a character in a different position
should not count as a match.

Is there any simpler/neater way than just a for loop running through
both strings and counting non-matching characters?

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


Re: How to check for single character change in a string?

2011-12-24 Thread Ian Kelly
On Sat, Dec 24, 2011 at 8:26 AM,   wrote:
> Can anyone suggest a simple/easy way to count how many characters have
> changed in a string?
>
> E.g. giving results as follows:-
>
>    abcdefg     abcdefh         1
>    abcdefg     abcdekk         2
>    abcdefg     gfedcba         6
>
>
> Note that position is significant, a character in a different position
> should not count as a match.
>
> Is there any simpler/neater way than just a for loop running through
> both strings and counting non-matching characters?

No, but the loop approach is pretty simple:

sum(a == b for a, b in zip(str1, str2))
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to check for single character change in a string?

2011-12-24 Thread Roy Smith
In article , tinn...@isbd.co.uk wrote:

> Can anyone suggest a simple/easy way to count how many characters have
> changed in a string?

Depending on exactly how you define "changed", you're probably talking 
about either Hamming Distance or Levenshtein Distance.  I would start 
with the wikipedia articles on both those topics and explore from there.

There are python packages for computing many of these metrics.  For 
example, http://pypi.python.org/pypi/python-Levenshtein/

> Is there any simpler/neater way than just a for loop running through
> both strings and counting non-matching characters?

If you don't care about insertions and deletions (and it sounds like you 
don't), then this is the way to do it.  It's O(n), and you're not going 
to get any better than that.  It's a one-liner in python:

>>> s1 = 'abcdefg'
>>> s2 = 'abcdekk'

>>> len([x for x in zip(s1, s2) if x[0] != x[1]])
2

But go read the wikipedia articles.  Computing distance between 
sequences is an interesting, important, and well-studied topic.  It's 
worth exploring a bit.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to check for single character change in a string?

2011-12-24 Thread Roy Smith
In article ,
 Roy Smith  wrote:

> >>> len([x for x in zip(s1, s2) if x[0] != x[1]])

Heh, Ian Kelly's version:

> sum(a == b for a, b in zip(str1, str2))

is cleaner than mine.  Except that Ian's counts matches and the OP asked 
for non-matches, but that's an exercise for the reader :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to check for single character change in a string?

2011-12-24 Thread Arnaud Delobelle
On 24 December 2011 16:10, Roy Smith  wrote:
> In article ,
>  Roy Smith  wrote:
>
>> >>> len([x for x in zip(s1, s2) if x[0] != x[1]])
>
> Heh, Ian Kelly's version:
>
>> sum(a == b for a, b in zip(str1, str2))
>
> is cleaner than mine.  Except that Ian's counts matches and the OP asked
> for non-matches, but that's an exercise for the reader :-)

Here's a variation on the same theme:

sum(map(str.__ne__, str1, str2))

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


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

2011-12-24 Thread Eelco
On Dec 24, 3:57 pm, Chris Angelico  wrote:
> On Sun, Dec 25, 2011 at 1:47 AM, Eelco  wrote:
> > a, middle::tuple, b = ::sequence
>
> Then it ought to be
>
> ::(a, middle::tuple, b) = ::sequence
>
> or something, because you're doing the same thing on both sides.
>
> ChrisA

Thats a fair point; something to think about. It all depends on how
you define the rules of course; im trying to stay as close as possible
to the original python rules, where the (un)packing of comma-seperated
identifiers is implicit. Probably best to keep it that way, from the
looks of it :).
-- 
http://mail.python.org/mailman/listinfo/python-list


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

2011-12-24 Thread Eelco
On Dec 24, 4:01 pm, Chris Angelico  wrote:
> On Sun, Dec 25, 2011 at 1:45 AM, Eelco  wrote:
> > Can you give an example of a construct in python where two whitespace
> > delimited identifiers are legal?
>
> What do you mean? Two identifiers, separated only by whitespace and no
> keyword or operator?
>
> def foo():
>     asdf
>     qwer
>
> Perfectly legal, two statements that probably don't do anything useful though.
>
> ChrisA

Thats not a fair point, but more nitpicking. Yes, I should have been
more precise: in python, 'whitespace' is not a single beast like in
most languages, but newlines have a special meaning. I was obviously
not talking about those. Want to try again?
-- 
http://mail.python.org/mailman/listinfo/python-list


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

2011-12-24 Thread Chris Angelico
On Sun, Dec 25, 2011 at 4:23 AM, Eelco  wrote:
> Thats not a fair point, but more nitpicking. Yes, I should have been
> more precise: in python, 'whitespace' is not a single beast like in
> most languages, but newlines have a special meaning. I was obviously
> not talking about those. Want to try again?

In that case I can't think of any, but at least now you've clarified
the question (by not denying the rest of it). It was somewhat
ambiguous.

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


Re: what does 'a=b=c=[]' do

2011-12-24 Thread Thomas Rachel

Am 21.12.2011 23:25 schrieb Eric:


Is it true that if I want to create an array or arbitrary size such
as:
for a in range(n):
   x.append()

I must do this instead?
x=[]
for a in range(n):
   x.append()


Of course - your x must exist before using it.

> Now to my actual question.  I need to do the above for multiple arrays

(all the same, arbitrary size).  So I do this:
x=y=z=[]
for a in range(n):
   x.append()
   y.append()
   z.append()
Also, is there a more pythonic way to do "x=[], y=[], z=[]"?


You could do:

def create_xyz(n):
for a in range(n):
yield , , \
)

x, y, z = zip(*create_xyz(11))

or, if you want x, y, z to be lists,

x, y, z = [list(i) for i in zip(*create_xyz(11))]

.


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


Re: what does 'a=b=c=[]' do

2011-12-24 Thread Thomas Rachel

Am 22.12.2011 00:48 schrieb Steven D'Aprano:

On Wed, 21 Dec 2011 18:20:16 -0500, Dennis Lee Bieber wrote:


For the amount of typing, it's easier to just do a straight line
tuple unpack


a,b,c = ([],[],[])


Note that tuples are created by the comma, not the round brackets (or
parentheses for any Americans reading). So the round brackets there are
strictly redundant:

a, b, c = [], [], []

The only times you need the brackets around a tuple is to control the
precedence of operations, or for an empty tuple.


IBTD:

a=((a, b) for a, b, c in some_iter)
b=[(1, c) for ]

Without the round brackets, it is a syntax error.


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


Re: what does 'a=b=c=[]' do

2011-12-24 Thread Thomas Rachel

Am 22.12.2011 00:20 schrieb Dennis Lee Bieber:


The key one is that lists ([] defines a list, not an array) are
"mutable". Your "7" is not mutable.


Strictly spoken, that's only a "side show" where the effect is visible.

The real key concept is that [] creates *one* object which is then 
assigned to the three names. That's the same for mutable and immutable 
objects.


But only the modification which happens on mutable objects turns it into 
a problem.


The rest o your explanation is 100% correct.


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


Re: How to check for single character change in a string?

2011-12-24 Thread Rick Johnson
On Dec 24, 11:09 am, Arnaud Delobelle  wrote:

> sum(map(str.__ne__, str1, str2))

Mirror, mirror, on the wall. Who's the cleanest of them all?
-- 
http://mail.python.org/mailman/listinfo/python-list


Is my IDLE problem caused by .idlerc? Permissions.

2011-12-24 Thread W. eWatson
I installed 64-bit Python 2.7.2 on Win 7. IDLE does appear as the second 
choice on right-click of a py file menu. However, nothing happens if I 
use it. If I try to execute idle from the cmd window, it complains about 
.idlerc\recent-files.lst


IOError: [Errno 13] Permission denied: 
'C:\\Users\\Wayne\\.idlerc\\recent-files.lst'


These are permissions for it.

Permissions as follows:
SYSTEM: All. From Full control to write
Account Unknown(S-1-5-21...): read&exec, Read
Wayne: (normal use) All. From Full control to write
Admin: All. From Full control to write
WMPNetwork:  Read

Comments?

.idlerc permissions are slightly different for Account Unknown.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Generator Question

2011-12-24 Thread GZ
I see. Thanks for the clarification.

On Dec 22, 12:35 am, Steven D'Aprano  wrote:
> On Wed, 21 Dec 2011 21:45:13 -0800, GZ wrote:
> > Now the question here is this:
>
> > def h():
> >     if condition=true:
> >        #I would like to return an itereator with zero length
> >     else:
> >        for ...:yieldx
>
> > In other words, when certain condition is met, I want toyieldnothing.
> > How to do?
>
> Actually, there's an even easier way.
>
> >>> def h():
>
> ...     if not condition:
> ...         for c in "abc":
> ...            yieldc
> ...
>
> >>> condition = False
> >>> list(h())
> ['a', 'b', 'c']
> >>> condition = True
> >>> list(h())
>
> []
>
> --
> Steven
>
>

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


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

2011-12-24 Thread Devin Jeanpierre
> If Python was ever 'fixed' to prevent this issue, I'm pretty sure we'd
> see an increase in the number of questions like the OP's.

What makes you so sure? Both models do make sense and are equally
valid, it's just that only one of them is true. Is it just because
people already used to Python would get confused?

-- Devin

On Sat, Dec 24, 2011 at 9:08 AM, alex23  wrote:
> On Dec 24, 6:25 pm, Steven D'Aprano  +comp.lang.pyt...@pearwood.info> wrote:
>> > It's
>> > much harder to figure out what's going wrong with an early-bound
>> > mutable.
>>
>> Only for those who don't understand, or aren't thinking about, Python's
>> object model. The behaviour of early-bound mutables is obvious and clear
>> once you think about it, but it does require you to think about what's
>> going on under the hood, so to speak.
>
> And here we've come full circle to the point of this thread.
>
> If Python was ever 'fixed' to prevent this issue, I'm pretty sure we'd
> see an increase in the number of questions like the OP's.
> --
> http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list


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

2011-12-24 Thread alex23
On Dec 25, 9:25 am, Devin Jeanpierre  wrote:
> > If Python was ever 'fixed' to prevent this issue, I'm pretty sure we'd
> > see an increase in the number of questions like the OP's.
>
> What makes you so sure? Both models do make sense and are equally
> valid, it's just that only one of them is true. Is it just because
> people already used to Python would get confused?

Because I believe that the source of confusion has far more to do with
mutable/immutable objects than with early/late binding. Masking or
'correcting' an aspect of Python's behaviour because novices make the
wrong assumption about it just pushes the problem elsewhere and
potentially makes the language inconsistent at the same time.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Adding an interface to existing classes

2011-12-24 Thread Spencer Pearson
On Dec 23, 9:13 am, Terry Reedy  wrote:
> On 12/22/2011 3:21 AM, Spencer Pearson wrote:
>
> > I'm writing a geometry package, with Points and Lines and Circles and
> > so on, and eventually I want to be able to draw these things on the
> > screen. I have two options so far for how to accomplish this, but
> > neither of them sits quite right with me, and I'd like the opinion of
> > comp.lang.python's wizened elders.
>
> > Option 1. Subclassing.
> > The most Pythonic way would seem to be writing subclasses for the
> > things I want to display, adding a ".draw(...)" method to each one,
> > like this:
> > Option 2. A "draw" function, with a function dictionary.
>
> Option 3? Add a draw method to existing classes, rather than subclassing?
>
> --
> Terry Jan Reedy

Thanks for the response! Do you mean something like this?
class Point(GeometricObject):
def intersect(self, other):
...
def union(self, other):
...
def draw(self, ...):
...

I'd like to avoid this, because... well, what I want is a geometry
package, and it seems to me that whistles and bells like GUI support
ought to be confined to subpackages. I'd look at this and think, "the
rest of the Point class deals with fundamental geometric reality.
What's this GUI method doing mixed in with my beautiful mathematical
purity?" Is this the wrong attitude to take?

Or did you mean this?
In file "geometry/gui.py":
def draw_point(point, ...):
...
Point.draw = draw_point

I've never modified an existing class before, and I fear the
unfamiliar. If that's what you meant... it's really an acceptable
thing to do? It seems like somebody might see "some_point.draw(...)"
and be confused by the method's absence in the Point class definition.

(A hybrid approach would be to say "draw = geometry.gui.draw_point"
inside the body of the Point class, setting the attribute there
instead of in gui.py, but that makes me uneasy for the same reason as
putting the function's full definition in the class.)

Thanks again,
-Spencer
-- 
http://mail.python.org/mailman/listinfo/python-list


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

2011-12-24 Thread alex23
On Dec 25, 12:39 am, Eelco  wrote:
> This is really going to be the last time I waste any words on this

Oh hey, don't feel you actually have to justify the bullshit you're
talking for my sake.

> In case of python, collection PACKING (not unpacking) is signaled by a
> construct that can be viewed as a type constraint.

_But no one does view it that way because it isn't_. No more so than
[] taking a string separated list of arguments and return a list is a
type constraint. _That's it's behaviour_.

We have a language construct that returns a tuple, because in the
context of what tuples are in Python, that makes sense. There are
_plenty_ of such constructs. You have still yet to show what adding
all of this ridiculous shit to a function signature provides that
coercing the resulting tuple to your own type doesn't.

> So here it is again, in terms every 5 year old can understand. Id like
> to do the exact same thing python is already doing. Except with a few
> more, and different symbols, to enable one to express a few different
> variants of behavior. Clear enough?

That you're a condescending douchebag with nothing of value to
contribute?

Crystal.

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


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

2011-12-24 Thread Devin Jeanpierre
> Because I believe that the source of confusion has far more to do with
> mutable/immutable objects than with early/late binding. Masking or
> 'correcting' an aspect of Python's behaviour because novices make the
> wrong assumption about it just pushes the problem elsewhere and
> potentially makes the language inconsistent at the same time.

That seems fairly silly -- foo.append(bar) obviously mutates
_something_ . Certainly it wasn't the source of my confusion when I
got caught on this. What makes you believe that the fundamental
confusion is about mutability?

(Also, if the change is applied everywhere, the language would not be
inconsistent.)

-- Devin

On Sat, Dec 24, 2011 at 7:10 PM, alex23  wrote:
> On Dec 25, 9:25 am, Devin Jeanpierre  wrote:
>> > If Python was ever 'fixed' to prevent this issue, I'm pretty sure we'd
>> > see an increase in the number of questions like the OP's.
>>
>> What makes you so sure? Both models do make sense and are equally
>> valid, it's just that only one of them is true. Is it just because
>> people already used to Python would get confused?
>
> Because I believe that the source of confusion has far more to do with
> mutable/immutable objects than with early/late binding. Masking or
> 'correcting' an aspect of Python's behaviour because novices make the
> wrong assumption about it just pushes the problem elsewhere and
> potentially makes the language inconsistent at the same time.
> --
> http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list


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

2011-12-24 Thread Rick Johnson
On Dec 24, 6:24 pm, alex23  wrote:

> That you're a condescending douchebag with nothing of value to
> contribute?
>
> Crystal.

Take it from me Eelco. Once Alex drops into your thread and starts
name calling, it's over my friend.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Adding an interface to existing classes

2011-12-24 Thread Ian Kelly
On Thu, Dec 22, 2011 at 1:21 AM, Spencer Pearson
 wrote:
> I see a problem with this, though. The intersection of two lines is
> (usually) an object of type Point. Since DrawableLine inherits from
> Line, this means that unless I redefine the "intersect" method in
> DrawableLine, the intersection of two DrawableLines will be a Point
> object, not a DrawablePoint. I don't want to saddle the user with the
> burden of converting every method output into its corresponding
> Drawable subclass, and I don't want to redefine every method to return
> an instance of said subclass. I see no other options if I continue
> down the subclassing path. Am I missing something?

You could solve this with a factory. Instead of having
Line.intersection() create a Point directly, have it call
self.factory.create_point().  In the drawing module, replace the
factory for the subclasses with one that creates drawable classes
instead.


> Option 2. A "draw" function, with a function dictionary.
> This feels weird, but is fairly simple to write, use, and extend. We
> have a module with a "draw_functions" dictionary that maps types onto
> functions, and a "draw" function that just looks up the proper type in
> the dictionary and calls the corresponding function. If you create
> your own object, you can just add a new entry to the dictionary. The
> implementation is simple enough to outline here:

This will also work, but inheritance complicates things a little.  Do
you do a type equality check or an isinstance() check when looking up
the type in the dictionary?  If the former, then somebody who
subclasses geometry.Line to create a GroovyLine subclass must add an
entry for GroovyLine to the dictionary, even if the drawing code is
the same.  The drawing code is not inherited.

But if you do an isinstance() check, then you need to be very careful
about how you check it.  If somebody creates a WavyLine subclass and
registers a different drawing method, then you need to make sure the
isinstance() check for the WavyLine implementation happens before the
regular Line implementation, or the wrong drawing code may get invoked
for WavyLine.  Probably the easiest way to do this correctly is to
follow the MRO that Python has conveniently already built for you.
Something like:

def draw(x, *args, **kwargs ):
for class_ in type(x).__mro__:
if class_ in draw_functions:
draw_functions[class_](*args, **kwargs)
break
else:
raise TypeError("don't know how to draw things of type "
"{0}".format(type(x)))

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


Re: Adding an interface to existing classes

2011-12-24 Thread Rick Johnson
On Dec 22, 2:21 am, Spencer Pearson  wrote:
> I'm writing a geometry package, with Points and Lines and Circles and
> so on, and eventually I want to be able to draw these things on the
> screen.

...which is the main reason for creating a geometry package in the
first place!. I mean, imaginary points and lines are great if you are
a theoretical mathematician, but for the rest of us earthlings,
plotted pixels are the "in thang" now-a-days.

> I have two options so far for how to accomplish this, but
> neither of them sits quite right with me, and I'd like the opinion of
> comp.lang.python's wizened elders.
>
> Option 1. Subclassing.
> The most Pythonic way would seem to be writing subclasses for the
> things I want to display, adding a ".draw(...)" method to each one,
> like this:
> class DrawablePoint( geometry.Point ):
>     class draw( self, ... ):
>         ...

"DrawablePoint"? I suppose there is an "ImaginaryPoint" somewhere in
this API? Geez

> When the time comes to draw things, I'll have some list of objects I
> want drawn, and say
> for x in to_draw:
>     x.draw(...)

Seems reasonable. Not the fastest approach, but a good start for a
very high level interface.

> I see a problem with this, though. The intersection of two lines is
> (usually) an object of type Point. Since DrawableLine inherits from
> Line,

Why the hell is "Drawable" inheriting from Line? I would think that a
"Line" would be "Drawable" object and NOT vice-versa? Am i wrong?

> this means that unless I redefine the "intersect" method in
> DrawableLine, the intersection of two DrawableLines will be a Point
> object, not a DrawablePoint.

OMFG!

> I don't want to saddle the user with the
> burden of converting every method output into its corresponding
> Drawable subclass, and I don't want to redefine every method to return
> an instance of said subclass. I see no other options if I continue
> down the subclassing path. Am I missing something?

Yes, a proper object hierarchy and API it seems @_@.

Spencer, i would re-think this entire project from the beginning. You
are trying to make an object out of everything. You don't need to make
an object of EVERYTHING. Ask yourself, what are the most basic objects
of a geometry library, and then report back to us your findings.

PS: I prefer option1 for these things as the OOP paradigm fits nicely.
I just hate to have modules of loose functions just lying about.

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


Re: Adding an interface to existing classes

2011-12-24 Thread Terry Reedy

On 12/24/2011 6:49 PM, Spencer Pearson wrote:

On Dec 23, 9:13 am, Terry Reedy  wrote:

On 12/22/2011 3:21 AM, Spencer Pearson wrote:


I'm writing a geometry package, with Points and Lines and Circles and
so on, and eventually I want to be able to draw these things on the
screen. I have two options so far for how to accomplish this, but
neither of them sits quite right with me, and I'd like the opinion of
comp.lang.python's wizened elders.



Option 1. Subclassing.
The most Pythonic way would seem to be writing subclasses for the
things I want to display, adding a ".draw(...)" method to each one,
like this:


There are people who would advocate a Drawable base class with a virtual 
or abstract .draw method and that DrawablePoint, etc, inherit from 
Drawable and Point.



Option 2. A "draw" function, with a function dictionary.


Option 3? Add a draw method to existing classes, rather than subclassing?



Thanks for the response! Do you mean something like this?
class Point(GeometricObject):
 def intersect(self, other):
 ...


I am interpreting this to mean that you have a world coordinate system 
for instances that have location and size.



 def union(self, other):
 ...
 def draw(self, ...):
 ...


Yes. I would consider that Option 0, the default, unless you have good 
reason to choose another. I would certainly include it on a list of options.



I'd like to avoid this, because... well, what I want is a geometry
package, and it seems to me that whistles and bells like GUI support
ought to be confined to subpackages. I'd look at this and think, "the
rest of the Point class deals with fundamental geometric reality.
What's this GUI method doing mixed in with my beautiful mathematical
purity?"


By default, all Python objects have a text representation method. I do 
not see that giving all concrete geometric objects (with a location and 
size) a visual representation is much different. I would use drawing 
functions that accept the coordinates and distances of your geometry 
world and translate to low-level pixel functions for a particular gui 
system. I agree that your geometrical objects should not know about 
pixels, screens, windows, and aspect ratios.


> Is this the wrong attitude to take?

It depends on *your* goal and values.


Or did you mean this?
In file "geometry/gui.py":
def draw_point(point, ...):
 ...
Point.draw = draw_point

I've never modified an existing class before, and I fear the
unfamiliar. If that's what you meant... it's really an acceptable
thing to do?


Yes, in my opinion. The advantage of this is putting all the draw 
methods together, and possibly having more than one one set. On the 
other hand, one needs to know the data attributes of each class to 
understand its draw method.



It seems like somebody might see "some_point.draw(...)"
and be confused by the method's absence in the Point class definition.


With either suboption, you should put an abstract .draw method in the 
GeometricObject base class.


I would look at various game, graph, geometry, and gui packages handle 
drawing for more ideas.


--
Terry Jan Reedy

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


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

2011-12-24 Thread rusi
On Dec 25, 5:32 am, Devin Jeanpierre  wrote:
> alex23 wrote:
> > Because I believe that the source of confusion has far more to do with
> > mutable/immutable objects than with early/late binding. Masking or
> > 'correcting' an aspect of Python's behaviour because novices make the
> > wrong assumption about it just pushes the problem elsewhere and
> > potentially makes the language inconsistent at the same time.

Thats hitting the nail on the head.

>
> That seems fairly silly -- foo.append(bar) obviously mutates
> _something_ . Certainly it wasn't the source of my confusion when I
> got caught on this. What makes you believe that the fundamental
> confusion is about mutability?

The confusion is not about mutability. Its about mutability and
parameter passing being non-orthogonal.

>
> (Also, if the change is applied everywhere, the language would not be
> inconsistent.)

Obviously that would depend on what the change is.
-- 
http://mail.python.org/mailman/listinfo/python-list


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

2011-12-24 Thread Lie Ryan

On 12/24/2011 07:25 PM, Steven D'Aprano wrote:

I'd use a function attribute.

def func(x, y=None):
   if y is None:
 y = func.default_y
   ...
func.default_y = []

That's awkward only if you believe function attributes are awkward.


I do. All you've done is move the default from *before* the function is
defined to *after* the function is defined, instead of keeping it in the
function definition. It's still separate, and if the function is renamed
your code stops working. In other words, it violates encapsulation of the
function.


Although we can solve that (default being after the function is defined) 
using a simple decorator:


def funcargs(**args):
def __decorate_with_args(func):
for k,v in args.items():
setattr(func, k, v)
return func
return __decorate_with_args

Usage:

@funcargs(foo=4)
def bar(baz):
return baz + bar.foo

et voila, we had just reinvented early binding default argument, with a 
much uglier syntax.


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


installing matplotlib in MacOs 10.6.8.

2011-12-24 Thread Alex Ter-Sarkissov
hi everyone, I run python 2.7.2. in Eclipse (recently upgraded from 2.6). I
have a problem with installing matplotlib (I found the version for python
2.7. MacOs 10.3, no later versions). If I run python in terminal using arch
-i386 python, and then

from matplotlib.pylab import *

and similar stuff, everything works fine. If I run python in eclipse or
just without arch -i386, I can import matplotlib as

from matplotlib import  *

but actually nothing gets imported. If I do it in the same way as above, I
get the message

no matching architecture in universal wrapper

which means there's conflict of versions or something like that. I tried
reinstalling the interpreter and adding matplotlib to forced built-ins, but
nothing helped. For some reason I didn't have this problem with numpy and
tkinter.

Any suggestions are appreciated.
-- 
http://mail.python.org/mailman/listinfo/python-list


Test None for an object that does not implement ==

2011-12-24 Thread GZ
Hi,

I run into a weird problem. I have a piece of code that looks like the
following:

f(, a=None, c=None):
assert  (a==None)==(c==None)


The problem is that == is not implemented sometimes for values in a
and c, causing an exception NotImplementedError.

I ended up doing assert (not a)==(not c), but I think this code has
other issues, for example, when a=[] and c=['a'], the assertion will
fail, although a is not None.

So how do I reliably test if a value is None or not?

Thanks,
gz
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Test None for an object that does not implement ==

2011-12-24 Thread Paul Rubin
GZ  writes:
> assert  (a==None)==(c==None)...
> So how do I reliably test if a value is None or not?

Equality is the wrong comparison to start with.  Use "a is None".
-- 
http://mail.python.org/mailman/listinfo/python-list