Re: Python and Qt4 Designer

2012-07-15 Thread Vincent Vande Vyvre
On 15/07/12 07:31, Michael Torrie wrote:
> On 07/14/2012 11:13 AM, rusi wrote:
>> I looked at the second link and find code like this:
>>
>> app = None if ( not app ): app = QtGui.QApplication([])
>>
>> Maybe I'm dense but whats that if doing there?
>>
>> Frankly I seem to be a bit jinxed with gui stuff.  A few days ago 
>> someone was singing the praises of some new themed tk stuff. I could 
>> not get the first two lines -- the imports -- to work and then gave 
>> up
> Since you haven't had any experience with gui development then probably
> loading ui files isn't the right place to start.  First principles
> (creating gui widgets from scratch) would be it.
>
> In any case, the line in question is quite simple.  It creates a
> QApplication object, which is basically the engine that drives all Qt
> applications.  Once you call .run() on it, it takes over and handles all
> the mouse events and such for you.  In fact you do not have any control
> over the program's execution from this point on, other than to define
> event call-back methods or functions that are called by the widgets when
> things happen, like mouse clicks.
>
> All gui toolkits operate this way.  You set up the widgets, then you run
> the main engine or main event loop and control never returns to your
> main program until something triggers the end (like closing a window or
> the quit menu item is pressed).
>
> Probably a complete working example is what you need to see, that is
> documented.  I primarily work with Gtk, but I'll whip up a Qt one
> tomorrow if I can.
Rusi is not the op, and his question is about these lines

app = None
if ( not app ):

not this one

app = QtGui.QApplication([])

which should be written like this

app = QtGui.QApplication(sys.argv)



-- 
Vincent V.V.
Oqapy  . Qarte
 . PaQager 

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


Implicit conversion to boolean in if and while statements

2012-07-15 Thread Andrew Berg
This has probably been discussed before, but why is there an implicit
conversion to a boolean in if and while statements?

if not None:
print('hi')
prints 'hi' since bool(None) is False.

If this was discussed in a PEP, I would like a link to it. There are so
many PEPs, and I wouldn't know which ones to look through.

Converting 0 and 1 to False and True seems reasonable, but I don't see
the point in converting other arbitrary values.

-- 
CPython 3.3.0b1 | Windows NT 6.1.7601.17803
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: lambda in list comprehension acting funny

2012-07-15 Thread Steven D'Aprano
On Sun, 15 Jul 2012 10:49:48 +1000, Chris Angelico wrote:

> On Sun, Jul 15, 2012 at 9:29 AM, Steven D'Aprano
>  wrote:
>> Not necessarily *compile* time, but the distinction is between when the
>> function is defined (which may at compile time, or it may be at run
>> time) versus when the function is called.
> 
> I'd treat the def/lambda statement as "compile time" and the () operator
> as "run time".

But function definitions occur at run time, not compile time -- they are 
executable statements, not instructions to the compiler to define a 
function.

For example:

py> dis("def f(x): return x+1")  # Python 3.2
  1   0 LOAD_CONST   0 (", line 1>)
  3 MAKE_FUNCTION0
  6 STORE_NAME   0 (f)
  9 LOAD_CONST   1 (None)
 12 RETURN_VALUE

The code object is pre-compiled at compile time, but the function and 
name-binding (the "def") doesn't occur until runtime.

At compile time, Python parses the source code and turns it into byte-
code. Class and function definitions are executed at run time, the same 
as any other statement.

I'm not sure if this is a difference that makes a difference or not; I 
think it is, but don't know enough about how closures and scoping rules 
work in other languages to be sure that it does make a difference.


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


Re: lambda in list comprehension acting funny

2012-07-15 Thread Chris Angelico
On Sun, Jul 15, 2012 at 6:32 PM, Steven D'Aprano
 wrote:
> At compile time, Python parses the source code and turns it into byte-
> code. Class and function definitions are executed at run time, the same
> as any other statement.

Between the parse step and the 'def' execution, a code object is
created. When you call it, that code object already exists. Nothing
else really matters, unless there's a bug in the Python optimizer or
something weird like that. The nearest thing Python _has_ to a
"compile time" is the execution of def.

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


Re: Implicit conversion to boolean in if and while statements

2012-07-15 Thread Chris Angelico
On Sun, Jul 15, 2012 at 6:34 PM, Andrew Berg  wrote:
> Converting 0 and 1 to False and True seems reasonable, but I don't see
> the point in converting other arbitrary values.

It's for convenience. Unfortunately, not all languages treat all types
the same way. It's very handy, though, to be able to use

if not foo: foo = some_initializer

when foo starts out as, say, None. Or []. Or, in fact, any other "empty" value.

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


Re: Implicit conversion to boolean in if and while statements

2012-07-15 Thread Stefan Behnel
Andrew Berg, 15.07.2012 10:34:
> This has probably been discussed before, but why is there an implicit
> conversion to a boolean in if and while statements?

There isn't. This has nothing to do with "if" or "while".

All objects have a truth value in Python, evaluating to True by default
(object), unless they implement the test themselves.

As Chris said, very convenient.

Stefan

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


Re: lambda in list comprehension acting funny

2012-07-15 Thread Terry Reedy

On 7/15/2012 4:32 AM, Steven D'Aprano wrote:

On Sun, 15 Jul 2012 10:49:48 +1000, Chris Angelico wrote:


On Sun, Jul 15, 2012 at 9:29 AM, Steven D'Aprano
 wrote:

Not necessarily *compile* time, but the distinction is between when the
function is defined (which may at compile time, or it may be at run
time) versus when the function is called.


I'd treat the def/lambda statement as "compile time" and the () operator
as "run time".


But function definitions occur at run time, not compile time -- they are
executable statements, not instructions to the compiler to define a
function.


The () operator is 'call time'. The main points are
a) the execution of def statements and lambda expressions and the 
execution of calls happen at different run times.

b) default arg objects are calculated at def/lambda time.
c) names in def bodies and lambda expressions are resolved at call time.
and
d) people more often forget c) when thinking about lambda expressions 
that for def statements.


--
Terry Jan Reedy

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


Re: Implicit conversion to boolean in if and while statements

2012-07-15 Thread Steven D'Aprano
On Sun, 15 Jul 2012 03:34:46 -0500, Andrew Berg wrote:

> This has probably been discussed before, 

By the hoary hosts of Hoggoth, has it ever!

> but why is there an implicit
> conversion to a boolean in if and while statements?

It's nothing to do with if and while. All Python objects are duck-typed 
as bools.

1) It's generally part of the duck-typing philosophy. If an object quacks 
like a bool, why not treat it as a bool?

2) It's useful and convenient for short-circuit boolean expressions such 
as any(), all(), and various things like:

for x in mylist or []: 
...

is better than:

if mylist is not None:
for x in mylist: 
...

3) Rather than distinguishing "true" from "false", a more useful 
dichotomy is between "something" and "nothing". Python includes a number 
of ways of spelling "nothing" of various types, such as:

None, 0, 0.0, '', [], {}, set()

and nearly everything else is "something".

4) Other languages such as Ruby, Javascript, PHP, Clojure and others also 
distinguish between true-like and false-like ("truthy" and "falsey") 
values. Although some of them have made some pretty weird and arbitrary 
choices for what counts as true-like and false-like, without Python's 
general principle that "nothing" values should be false.

(E.g. Javascript considers Boolean(false) to be a true value!!!)

5) Prior to Python 2.2, there was no bool type and no True and False 
values. In fact, here is an impassioned plea from an educator begging 
Guido not to introduce True and False to the language, because duck-typed 
truthy/falsey values are *so much better*.

http://groups.google.com/group/comp.lang.python/msg/2de5e1c8384c0360?hl=en

Sadly, or happily, Python did grow True and False values, but the 
fundamental distinction between something and nothing still exists.

(For the record, I can only think of one trap for the unwary: time 
objects are false at *exactly* midnight.)


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


Re: [OT] Simulation Results Managment

2012-07-15 Thread Neal Becker
Dieter Maurer wrote:

> moo...@yahoo.co.uk writes:
>> ...
>> Does pickle have any advantages over json/yaml?
> 
> It can store and retrieve almost any Python object with almost no effort.
> 
> Up to you whether you see it as an advantage to be able to store
> objects rather than (almost) pure data with a rather limited type set.
> 
> 
> Of course, "pickle" is a proprietary Python format. Not so easy to
> decode it with something else than Python. In addition, when
> you store objects, the retrieving application must know the classes
> of those objects -- and its knowledge should not be too different
> from how those classes looked when the objects have been stored.
> 
> 
> I like very much to work with objects (rather than with pure data).
> Therefore, I use "pickle" when I know that the storing and retrieving
> applications all use Python. I use pure (and restricted) data formats
> when non Python applications come into play.

Typically what I want to do is post-process (e.g. plot) results using python 
scripts, so using pickle is great for that.

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


Re: 2 + 2 = 5

2012-07-15 Thread samuel . marks
On Friday, July 6, 2012 8:39:58 AM UTC+10, Andrew Cooper wrote:
> On 05/07/2012 22:46, Evan Driscoll wrote:
> > On 01/-10/-28163 01:59 PM, Alexander Blinne wrote:
> >> 5+0 is actually 4+0, because 5 == 4, so 5+0 gives 4.
> >> 5+1 is actually 4+1, which is 5, but 5 is again 4.
> >> 5+2 is 4+2 which is 6.
> > 
> > Now all I can think is "Hoory for new math, new-hoo-hoo math" 
> :-)
> > 
> > Evan
> 
> It wont do you a bit of good to read new math!
> 
> (My mind was on exactly the same track)
> 
> ~Andrew

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


Re: Keeping the Console Open with IDLE

2012-07-15 Thread rantingrickjohnson
On Friday, February 20, 2009 9:41:42 AM UTC-6, David Smith wrote:

> What I meant was open open the command prompt, type cd, space, DO NOT
> hit enter yet.  Drag the folder with your script into the command prompt
> window.  Then go to the command prompt window and hit enter.  This
> should compose a command similar to the following:

And why the hell would you resort to such contrived contortions as that? Are 
you masochistic? DoubleClicking an icon will take me less that one second. How 
long does this sequence take:

 1. Open a command prompt
 2. type "c"
 3. type "d"
 4. type "space"
 5. hover over the folder icon with your mouse
 5.5. Oops, i missed. Go back to step 5!
 6. Mouse click the file "icon"
 7. Mouse drag the file "icon"
 8. Position the mouse over prompt window
 9. Release the "icon" 
10. Press the "Enter" key

Can anybody say "!Ay, caramba!"? 

Besides, you can skip most of those steps by Shift+RightClicking the file icon 
and choosing "Open Command Window Here". But, why the hell would you EVEN do 
that when two simple clicks will suffice?

"practicality beats purity"



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


Re: Keeping the Console Open with IDLE

2012-07-15 Thread Chris Angelico
On Mon, Jul 16, 2012 at 1:35 AM,   wrote:
> Besides, you can skip most of those steps by Shift+RightClicking the file 
> icon and choosing "Open Command Window Here".

That's not standard. Me, I can invoke git bash anywhere I want it, but
that doesn't mean I'd recommend installing git just so that people can
get command lines with less steps.

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


Re: Keeping the Console Open with IDLE

2012-07-15 Thread Rick Johnson
On Sunday, July 15, 2012 10:57:00 AM UTC-5, Chris Angelico wrote:
> On Mon, Jul 16, 2012 at 1:35 AM,   wrote:
> > Besides, you can skip most of those steps by Shift+RightClicking
> > the file icon and choosing "Open Command Window Here".
>
> That's not standard. Me, I can invoke git bash anywhere I want it, but
> that doesn't mean I'd recommend installing git just so that people can
> get command lines with less steps.

I don't understand Chris? It's obvious that the OP is on a windows box; for 
which no installation is required. 

And, what is so egregious about "less steps"(sic)? Do you prefer to be 
unproductive? Did you forget the lazy programmers creed? Is your employer 
paying you by the hour? ...all good questions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Implicit conversion to boolean in if and while statements

2012-07-15 Thread Ian Kelly
On Sun, Jul 15, 2012 at 4:56 AM, Steven D'Aprano
 wrote:
> (For the record, I can only think of one trap for the unwary: time
> objects are false at *exactly* midnight.)

Ugh, that's irritating.  I can't think of any scenario where I would
ever want the semantics "if timeval (is not midnight):".  This
reinforces the point that if you only want to test whether you have
None, you should use "is not None" rather than relying on __bool__.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Simulation Results Managment

2012-07-15 Thread rusi
On Jul 15, 11:35 am, Dieter Maurer  wrote:
> moo...@yahoo.co.uk writes:
> > ...
> > Does pickle have any advantages over json/yaml?
>
> It can store and retrieve almost any Python object with almost no effort.
>
> Up to you whether you see it as an advantage to be able to store
> objects rather than (almost) pure data with a rather limited type set.
>
> Of course, "pickle" is a proprietary Python format. Not so easy to
> decode it with something else than Python. In addition, when
> you store objects, the retrieving application must know the classes
> of those objects -- and its knowledge should not be too different
> from how those classes looked when the objects have been stored.
>
> I like very much to work with objects (rather than with pure data).
> Therefore, I use "pickle" when I know that the storing and retrieving
> applications all use Python. I use pure (and restricted) data formats
> when non Python applications come into play.

Pickle -> JSON -> Yaml
are roughly in increasing order of human-friendliness and decreasing
order of machine friendliness (where machine means python 'machine')

This means that
 - Pickle is most efficient, Yaml least
 - Pickle comes with python from as far back as I know
   Json started coming somewhere round 2.5 (I think)
   (py)yaml needs to be installed separately
 - reading pickled data will spoil your eyes whereas yaml is pleasant
to read (just like python)

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


Re: Keeping the Console Open with IDLE

2012-07-15 Thread Chris Angelico
On Mon, Jul 16, 2012 at 2:19 AM, Rick Johnson
 wrote:
> On Sunday, July 15, 2012 10:57:00 AM UTC-5, Chris Angelico wrote:
>> On Mon, Jul 16, 2012 at 1:35 AM,   wrote:
>> > Besides, you can skip most of those steps by Shift+RightClicking
>> > the file icon and choosing "Open Command Window Here".
>>
>> That's not standard. Me, I can invoke git bash anywhere I want it, but
>> that doesn't mean I'd recommend installing git just so that people can
>> get command lines with less steps.
>
> I don't understand Chris? It's obvious that the OP is on a windows box; for 
> which no installation is required.

I have here a Windows XP system (shh, it doesn't know there's Linux
between it and the hardware) which has no such context-menu item. Ergo
it is not standard and cannot be assumed to be on the target computer,
and installation IS required.

> And, what is so egregious about "less steps"(sic)? Do you prefer to be 
> unproductive? Did you forget the lazy programmers creed? Is your employer 
> paying you by the hour? ...all good questions.

And if you're going to quibble about "fewer steps" then you should
probably have an apostrophe in "lazy programmers' creed". Just sayin'.

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


Re: Implicit conversion to boolean in if and while statements

2012-07-15 Thread Rick Johnson
On Sunday, July 15, 2012 11:19:16 AM UTC-5, Ian wrote:
> On Sun, Jul 15, 2012 at 4:56 AM, Steven D'Aprano
>  wrote:
> > (For the record, I can only think of one trap for the unwary: time
> > objects are false at *exactly* midnight.)
> 
> Ugh, that's irritating.  I can't think of any scenario where I would
> ever want the semantics "if timeval (is not midnight):".  This
> reinforces the point that if you only want to test whether you have
> None, you should use "is not None" rather than relying on __bool__.

I think this issue is not so much a "bool test" vs "type test", but more an 
ambiguous syntax issue. Consider this:

## EXAMPLE A ##
py> if money:
... do_something()

The syntax "if money" implies we are testing/measuring some attribute of 
"money", but what exactly about money are we testing/measuring? The problem 
lies in the syntax. To understand this syntax, we must first interpret what 
*IF* means, and we should *NEVER* need to interpret such a well defined word as 
*IF*! This syntax is far too opaque. Consider the alternative:

## EXAMPLE B ##
py> if bool(money):
... do_something()

Now we have a hint. Even if we don't understand the inner workings of the 
"bool" function, we *do* understand that the statement "bool(money)" *must* 
return True or the block *will not* execute. 

We must NEVER present "if" in such confusing manner as ExampleA. I believe 
Guido made a grave mistake allowing this syntax to flourish. His intentions 
where noble, to save people a few keystrokes, but all he accomplished was to 
pave a road directly into hell. 

 "Explict is better than Implict"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Implicit conversion to boolean in if and while statements

2012-07-15 Thread Andrew Berg
On 7/15/2012 5:56 AM, Steven D'Aprano wrote:
> 3) Rather than distinguishing "true" from "false", a more useful 
> dichotomy is between "something" and "nothing". Python includes a number 
> of ways of spelling "nothing" of various types, such as:
> 
> None, 0, 0.0, '', [], {}, set()
> 
> and nearly everything else is "something".
Okay, I see the value in this, but I don't understand why None has a
truth value. I would expect None to mean "doesn't exist" or "unknown" or
something like that - e.g., a value of 0 means 0 jelly beans in the jar
and None means there isn't a jar.

FWIW, I have, for a reason I forget, gotten into the habit of writing
"if x is not None" when testing for None. However, I have not been
writing "if x is True: ..."/"elif x is False: ..."/"else: 'ruh-roh'"
when testing for True (in cases where a value of True or False makes
sense, but any other value would not). Should I?

-- 
CPython 3.3.0b1 | Windows NT 6.1.7601.17803
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Implicit conversion to boolean in if and while statements

2012-07-15 Thread Andrew Berg
On 7/15/2012 11:19 AM, Ian Kelly wrote:
> Ugh, that's irritating.  I can't think of any scenario where I would
> ever want the semantics "if timeval (is not midnight):".
It's not implemented with such a test, but
logging.handlers.TimedRotatingFileHandler has an option to rollover at
midnight.
-- 
CPython 3.3.0b1 | Windows NT 6.1.7601.17803
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Request for useful functions on dicts

2012-07-15 Thread Ian Kelly
On Sat, Jul 14, 2012 at 5:56 PM, Leif  wrote:
> Hi, everybody. I am trying to collect all the functions I've found useful for 
> working with dicts into a library:
>
> https://github.com/leifp/dictutil
>
> If you have a favorite dict-related func / class, or know of similar 
> projects, please let me know (or open an issue on github). Bear in mind that 
> the functions don't even have to come from python; if you have a favorite PHP 
> / APL / COBOL / etc associative array function, that's fair game.

Nothing in particular comes to mind, but I'll be happy to critique
what you've already got.

One thing that bothers me a bit is that get_in will accept any
iterable, but set_in and update_in can only accept a sequence in order
to do the slicing.  Here's an alternate implementation for set_in that
takes any iterable:

def set_in(d, ks, v):
tmp = d
i = None
for i, next_key in enumerate(ks):
if i > 0:
tmp = tmp.setdefault(current_key, {})
current_key = next_key
if i is None:
raise KeyError("Empty keys iterable")
tmp[current_key] = v

update_in could be rewritten similarly.  You might also notice that
I'm not returning d here.  That's because the Pythonic way is to
either create a new object and return it, or mutate the existing
object and return None.  If you mutate the existing object and return
it, that can lead to confusion about which style the method takes.
This is why list.append (for example) always returns None.

In Python 2.7+, intersection and difference could be written using
dictviews, which act like sets.

partition_on_value, partition_on_key:  The only difference between
these is whether it passes the key or the value to the predicate.  You
could just pass both and let the predicate decide which one (or both)
to use, and then you only need a single function.  Also, why a
predicate specifically?  This could be generalized to partition any
equivalence relation, not just those with only two equivalence
classes:

def partition(f, d):
"""Partition the dict according to an equivalence relation.

Calls f(key, value) for all (key, value) pairs in the dict d.  The return
value of f must be hashable.
Returns a new dict where the keys are distinct return values of f, and the
values are dicts containing the equivalence classes distinguished by those
return values.
"""
partition = defaultdict(dict)
for k, v in d.iteritems():
partition[f(k, v)][k] = v
return partition

If you still wanted the predicate semantics, you could then define
that as a wrapper:

def partition_pred(f, d):
p = partition(lambda k,v: bool(f(k,v)), d)
return p[True], p[False]

issubdict could be implemented as a subset operation.  I haven't timed
it so it may not really be any faster, but this way the looping is in
C instead of in Python:

def issubdict(d1, d2):
return set(d1.items()).issubset(d2.items())

Finally, isempty(d) is basically equivalent to "not d", which is both
shorter and faster.

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


Re: Implicit conversion to boolean in if and while statements

2012-07-15 Thread Ian Kelly
On Sun, Jul 15, 2012 at 11:16 AM, Andrew Berg  wrote:
> On 7/15/2012 11:19 AM, Ian Kelly wrote:
>> Ugh, that's irritating.  I can't think of any scenario where I would
>> ever want the semantics "if timeval (is not midnight):".
> It's not implemented with such a test, but
> logging.handlers.TimedRotatingFileHandler has an option to rollover at
> midnight.

Nor could it be implemented with such a test, since the rollover check
would then have to run at exactly midnight for the test to evaluate
false.  If it were off by 1 microsecond, it would miss it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Implicit conversion to boolean in if and while statements

2012-07-15 Thread Ian Kelly
On Sun, Jul 15, 2012 at 10:50 AM, Rick Johnson
 wrote:
> I think this issue is not so much a "bool test" vs "type test", but more an 
> ambiguous syntax issue. Consider this:
>
> ## EXAMPLE A ##
> py> if money:
> ... do_something()
>
> The syntax "if money" implies we are testing/measuring some attribute of 
> "money", but what exactly about money are we testing/measuring? The problem 
> lies in the syntax. To understand this syntax, we must first interpret what 
> *IF* means, and we should *NEVER* need to interpret such a well defined word 
> as *IF*! This syntax is far too opaque. Consider the alternative:
>
> ## EXAMPLE B ##
> py> if bool(money):
> ... do_something()
>
> Now we have a hint. Even if we don't understand the inner workings of the 
> "bool" function, we *do* understand that the statement "bool(money)" *must* 
> return True or the block *will not* execute.

So now instead of having to understand how "if" handles arbitrary
values, we have to understand how "bool" handles arbitrary values.
How is that an improvement?

What should "if" do if presented a value that isn't True or False?
Raise a TypeError?

Next thing we know, people get so used to wrapping everything they
present to "if" in a "bool()" call, that they start writing silly
things like "if bool(x == 7)" and "if bool(isinstance(x, int))".  Why?
 Because it's faster and easier to automatically wrap the value in
"bool" than it is to put in the effort to verify that the value will
always be a bool to begin with in order to avoid a useless and
annoying exception.  At the point that happens, the "bool()" is
effectively just part of the if syntax, and we're back to where we
started.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Initial nose experience

2012-07-15 Thread python
Hi Roy,

> I've been using unittest for many years, but have steadfastly 
(perhaps stubbornly) avoided newfangled improvements like nose.  
I finally decided to take a serious look at nose.

Thanks for sharing your nose experience.

What motivated you to migrate from unittest to nose?

After years of using unittest, what would you say are the pros and
cons of nose?

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


Re: Implicit conversion to boolean in if and while statements

2012-07-15 Thread Rick Johnson
On Sunday, July 15, 2012 1:01:58 PM UTC-5, Ian wrote:

> So now instead of having to understand how "if" handles arbitrary
> values, we have to understand how "bool" handles arbitrary values.
> How is that an improvement?

Because we are keeping the condition consistent. We are not relying on implicit 
resolution of an object's value based on some dark, esoteric and inconsistent 
rules that defy all normal logic.

> What should "if" do if presented a value that isn't True or False?
> Raise a TypeError?

YES! Because IT IS the author's responsibility to present a condition that 
evaluates to either True or False. Anything else would be ridiculously 
inconsistent.

> Next thing we know, people get so used to wrapping everything they
> present to "if" in a "bool()" call, that they start writing silly
> things like "if bool(x == 7)" and "if bool(isinstance(x, int))".  

We cannot prevent morons from doing stupid things. "x==7" IS an explicit 
statement that evaluates to either True or False. Likewise, isinstance(obj, 
type) is a function that evaluates to either True or False. Wrapping either 
example in a bool call is redundant and only obfuscates the meaning. True 
equals True and False equal False. Why do you need to test that truth?

The only time you will be forced to use the bool is when you are NOT using rich 
comparisons or NOT using truth testing functions in a condition. The following 
require NO bool function:

obj == obj -> bool
obj != obj -> bool
obj > obj -> bool
obj < obj -> bool
obj >= obj -> bool
obj <= obj -> bool
isinstance(obj, type) -> bool
callable(obj) -> bool
hasattr(obj, name) -> bool
issubclass(obj, name) -> bool
..along with any function that returns a bool

Whereas: 
"if obj" -> Some esoteric semantics that defies all logic!

> Why?
> Because it's faster and easier to automatically wrap the value in
> "bool" than it is to put in the effort to verify that the value will
> always be a bool to begin with in order to avoid a useless and
> annoying exception.  

No, because we want our code to be EXPLICIT and consistent! Remember, writing 
obfuscated code is easy, however, interpreting obfuscated code is difficult! A 
good measure of your programming skill is to see how easily your code is read 
by the majority. 

 """If it's difficult to explain, it's probably a bad idea""". 

"if blah" is difficult to explain, whereas "if bool(blah)" is not.   

> At the point that happens, the "bool()" is
> effectively just part of the if syntax, and we're back to where we
> started.

That's a ridiculous conclusion. See points above^^^

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


Re: Initial nose experience

2012-07-15 Thread Roy Smith
In article ,
 pyt...@bdurham.com wrote:

> Hi Roy,
> 
> > I've been using unittest for many years, but have steadfastly 
> (perhaps stubbornly) avoided newfangled improvements like nose.  
> I finally decided to take a serious look at nose.
> 
> Thanks for sharing your nose experience.
> 
> What motivated you to migrate from unittest to nose?

Mostly I was just looking for a better way to run our existing tests.  
We've got a bunch of tests written in standard unittest, but no good way 
to start at the top of the tree and run them all with a single command.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: lambda in list comprehension acting funny

2012-07-15 Thread Hans Mulder
On 15/07/12 10:44:09, Chris Angelico wrote:
> On Sun, Jul 15, 2012 at 6:32 PM, Steven D'Aprano
>  wrote:
>> At compile time, Python parses the source code and turns it into byte-
>> code. Class and function definitions are executed at run time, the same
>> as any other statement.
> 
> Between the parse step and the 'def' execution, a code object is
> created. When you call it, that code object already exists. Nothing
> else really matters, unless there's a bug in the Python optimizer or
> something weird like that. The nearest thing Python _has_ to a
> "compile time" is the execution of def.
> 
> ChrisA

"Compile time" is the phase when your Python code is turned into byte
code, or a SyntaxError is raised.  In this phase, a "code object" is
created for the function.

"Function definition time" is when the "def" command is executed.
In this phase, default arguments are computed, and a "function object"
is created.  Among the attributes of the function object are the code
object, and "cell" objects containing the bindings for its non-local
variables.  These bindings are used to read the variable's current
value at the time the function uses the variable.


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


Re: Request for useful functions on dicts

2012-07-15 Thread Leif
Thanks for the suggestions, Ian!  I implemented most of them and pushed the 
code.

> That's because the Pythonic way is to either create a new object and
> return it, or mutate the existing object and return None.

You're saying what I was already thinking.

> In Python 2.7+, intersection and difference could be written using
> dictviews, which act like sets.

I'm debating with myself right now whether to support 2.5 and 2.6.

> def partition(f, d):

Good idea, thanks.

> issubdict could be implemented as a subset operation.  I haven't timed

The current implementation is a bit faster, and it's quite a bit faster on the 
common (for me) case, where one argument is much smaller than the other.  I 
wrote it that way because if m=len(first), n=len(second), the amount of work is 
O(min(m,n)).  Your implementation is O(m + n).  Not really a big deal, unless 
e.g. m << n. 

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


Re: Implicit conversion to boolean in if and while statements

2012-07-15 Thread Terry Reedy

On 7/15/2012 12:19 PM, Ian Kelly wrote:

On Sun, Jul 15, 2012 at 4:56 AM, Steven D'Aprano
 wrote:

(For the record, I can only think of one trap for the unwary: time
objects are false at *exactly* midnight.)


Ugh, that's irritating.  I can't think of any scenario where I would
ever want the semantics "if timeval (is not midnight):".  This


When printing time tables, midnight may be either 24:00 or 0:00, 
depending on whether it is the end or start of a journey. That could, of 
course, be done by explicit if time == midnight: rather than if not time:.


Whether to change the current behavior was discussed on python-ideas a 
couple of months ago. I believe inertia and back-compatibity and the 
rare use case won.


> reinforces the point that if you only want to test whether you have
> None, you should use "is not None" rather than relying on __bool__.

Right.

--
Terry Jan Reedy



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


Re: Implicit conversion to boolean in if and while statements

2012-07-15 Thread Terry Reedy

On 7/15/2012 1:02 PM, Andrew Berg wrote:

On 7/15/2012 5:56 AM, Steven D'Aprano wrote:

3) Rather than distinguishing "true" from "false", a more useful
dichotomy is between "something" and "nothing". Python includes a number
of ways of spelling "nothing" of various types, such as:

 None, 0, 0.0, '', [], {}, set()

and nearly everything else is "something".

Okay, I see the value in this, but I don't understand why None has a
truth value.


Because everything does (or should).

> I would expect None to mean "doesn't exist" or "unknown" or

something like that - e.g., a value of 0 means 0 jelly beans in the jar
and None means there isn't a jar.

FWIW, I have, for a reason I forget, gotten into the habit of writing
"if x is not None" when testing for None.


If x might possibly be any other false value (as is, I think, the usual 
case), that is the right thing to do. Even if no other false value is 
possible, I would still use 'is not None' just to be clear what the 
false alternative is, and to guard against mistakes (like not knowing 
that time values can be false) or code changes that add the possibility 
of ohter false values.



However, I have not been
writing "if x is True: ..."/"elif x is False: ..."/"else: 'ruh-roh'"
when testing for True (in cases where a value of True or False makes
sense, but any other value would not). Should I?


If you only want to execute the if branch when x is literally the bool 
object True and x could be some other non-bool true value such as 1 or 
'a' or [1], etc, then you should.


If x is guaranteed to be True or False, which is the case you more or 
less proposed, then you should not. For instance, "if isinstance(x, int) 
is True:" or "if (n > 3) is True:" are redundant.


--
Terry Jan Reedy



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


Re: Implicit conversion to boolean in if and while statements

2012-07-15 Thread Chris Angelico
On Mon, Jul 16, 2012 at 4:56 AM, Rick Johnson
 wrote:
> On Sunday, July 15, 2012 1:01:58 PM UTC-5, Ian wrote:
>
>> So now instead of having to understand how "if" handles arbitrary
>> values, we have to understand how "bool" handles arbitrary values.
>> How is that an improvement?
>
> Because we are keeping the condition consistent. We are not relying on 
> implicit resolution of an object's value based on some dark, esoteric and 
> inconsistent rules that defy all normal logic.
>
>> What should "if" do if presented a value that isn't True or False?
>> Raise a TypeError?
>
> YES! Because IT IS the author's responsibility to present a condition that 
> evaluates to either True or False. Anything else would be ridiculously 
> inconsistent.

Then the construct "if bool(some_condition):" is redundant. What
you've described is a viable system (REXX, for instance, demands that
an IF statement be given strictly either a 1 or a 0 (there's no True
and False values, but you're not allowed to use 527 as a True value,
it has to be 1)), but it's still redundant to attempt the cast. For
instance, this REXX function will logically negate a value twice, thus
forcing it to boolean:

bool: procedure
return \\arg(1)

But if it's given a non-bool, it'll just bomb, exactly the same as the
if statement would. So Ian's point still stands.

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


Re: Implicit conversion to boolean in if and while statements

2012-07-15 Thread Ranting Rick
On Jul 15, 4:53 pm, Chris Angelico  wrote:
> Then the construct "if bool(some_condition):" is redundant.

Wrong again, pay attention Chris!

It's ONLY redundant IF "some_condition" is a rich comparison: like
"(a==b)" OR a boolean function: like "callable(a)".

If HOWEVER we want to "truth test" an object (as in: "if obj") we
should be FORCED to use the bool! Why? Because explicit is better than
implicit and readability counts if we want to create maintainable code
bases!

if bool(obj) and a==b: # Correct!
if obj and a==b:   # Incorrect!

Both lines of code currently produce the same result because
"somebody" decided to give objects esoteric boolean values. Sure, we
saved a few key stokes in a condition, but sadly at the cost of
readability and consistency. I see no reason why choosing implicit
resolution is better than explicit resolution. Saving six keystrokes
is simply not enough!

Python's motto has always been "readability counts", and for that
reason, we should return to Explicit Boolean Resolution if we want to
adhere to those principals.
-- 
http://mail.python.org/mailman/listinfo/python-list


Diagramming code

2012-07-15 Thread hamilton

Is there any software to help understand python code ?

Thanks

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


Re: Diagramming code

2012-07-15 Thread Chris Rebert
On Sun, Jul 15, 2012 at 6:26 PM, hamilton  wrote:
> Subject: Diagramming code
>
> Is there any software to help understand python code ?

What sort of diagrams? Control flow diagrams? Class diagrams? Sequence
diagrams? Module dependency diagrams? There are many different types
you could be referring to. Here's a relatively comprehensive list:
http://en.wikipedia.org/wiki/Unified_Modeling_Language#Diagrams_overview

Regards,
Chris
--
UML: Kill it with fire!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Implicit conversion to boolean in if and while statements

2012-07-15 Thread Chris Angelico
On Mon, Jul 16, 2012 at 11:21 AM, Ranting Rick
 wrote:
> If HOWEVER we want to "truth test" an object (as in: "if obj") we
> should be FORCED to use the bool! Why? Because explicit is better than
> implicit and readability counts if we want to create maintainable code
> bases!
>
> if bool(obj) and a==b: # Correct!
> if obj and a==b:   # Incorrect!

That still doesn't answer the question of what bool(obj) should do if
obj is not a bool, and why if can't do the exact same thing, since if,
by definition, is looking for a boolean state selector.

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


Re: Diagramming code

2012-07-15 Thread hamilton

On 7/15/2012 7:38 PM, Chris Rebert wrote:

On Sun, Jul 15, 2012 at 6:26 PM, hamilton  wrote:

Subject: Diagramming code

Is there any software to help understand python code ?


What sort of diagrams? Control flow diagrams? Class diagrams? Sequence
diagrams? Module dependency diagrams? There are many different types
you could be referring to. Here's a relatively comprehensive list:
http://en.wikipedia.org/wiki/Unified_Modeling_Language#Diagrams_overview

Regards,
Chris
--
UML: Kill it with fire!



OK then, let me ask, how do you guys learn/understand large projects ?

hamilton

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


Re: Diagramming code

2012-07-15 Thread Chris Rebert
On Sun, Jul 15, 2012 at 6:57 PM, hamilton  wrote:
> On 7/15/2012 7:38 PM, Chris Rebert wrote:
>>
>> On Sun, Jul 15, 2012 at 6:26 PM, hamilton  wrote:
>>>
>>> Subject: Diagramming code
>>>
>>> Is there any software to help understand python code ?
>>
>> What sort of diagrams? Control flow diagrams? Class diagrams? Sequence
>> diagrams? Module dependency diagrams? There are many different types
>> you could be referring to. Here's a relatively comprehensive list:
>> http://en.wikipedia.org/wiki/Unified_Modeling_Language#Diagrams_overview
>>
>> Regards,
>> Chris
>> --
>> UML: Kill it with fire!
>
> OK then, let me ask, how do you guys learn/understand large projects ?

In case you're responding to my trailing semi-satirical comment, let
me clarify: I was remarking on UML specifically, not software-related
diagrams in general.

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


Re: Implicit conversion to boolean in if and while statements

2012-07-15 Thread Steven D'Aprano
On Sun, 15 Jul 2012 10:19:16 -0600, Ian Kelly wrote:

> On Sun, Jul 15, 2012 at 4:56 AM, Steven D'Aprano
>  wrote:
>> (For the record, I can only think of one trap for the unwary: time
>> objects are false at *exactly* midnight.)
> 
> Ugh, that's irritating.  I can't think of any scenario where I would
> ever want the semantics "if timeval (is not midnight):".

Yes, it is a genuine gotcha. Time values are numbers, and zero is falsey, 
so midnight is falsey even though it shouldn't be.

There's no good solution here, since we have a conflict between treating 
time values as time values ("midnight is nothing special") and as numbers 
("midnight == 0 which is falsey"). The only "solution" is to throw out 
duck-typing of boolean values, which is tossing the baby out with the 
bathwater -- bool duck-typing works fine for everything else.


> This
> reinforces the point that if you only want to test whether you have
> None, you should use "is not None" rather than relying on __bool__.

Often you should, but I didn't mention anything about testing for None. 
Testing objects in a boolean context is more than just testing for None.

I have just written a bunch of code with about two dozen examples similar 
to this:

for item in (seq or []):
do_something_with(item)

iterates over seq if it is non-empty, or the empty list. Writing it like 
this would be more painful, more complex, less readable and less 
idiomatic:

if seq is not None:
for item in seq:
do_something_with(item)


not to mention completely unnecessary if you have already checked that 
seq is either None or a sequence, and not some other arbitrary value.

(If seq really could be any type at all, then an explicit identity test 
against None is required.)


One of my favourites:

value = (dict or {}).get('key')

instead of:

value = None if dict is None else dict.get('key')



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


Re: Implicit conversion to boolean in if and while statements

2012-07-15 Thread Devin Jeanpierre
On Sun, Jul 15, 2012 at 9:51 PM, Chris Angelico  wrote:
>> if bool(obj) and a==b: # Correct!
>> if obj and a==b:   # Incorrect!
>
> That still doesn't answer the question of what bool(obj) should do if
> obj is not a bool, and why if can't do the exact same thing, since if,
> by definition, is looking for a boolean state selector.

If can obviously do the exact same thing -- it does, in Python.

I don't agree with the angle that Rick is spinning, so let me write my
own: By forcing the objects in conditional to be booleans, you are
forced to do something to non-booleans to convert them. By doing so,
you will help inform the reader what the non-boolean is, which makes
it easier for them to figure out the code.

For example, instead of "if stack:" or "if bool(stack):", we could use
"if stack.isempty():". This line tells us explicitly that stack is a
container. Or instead of "if dist:" or "if bool(dist):" we could use
"if dist == 0:". This tells us explicitly that stack is a number.
Supposedly this makes it easier to read code. It certainly reads more
like English! :)

As far as I know, the only use of having a polymorphic boolean
conversion is reducing the amount of typing we do. Generally objects
with otherwise different interfaces are not interchangeable just
because they can be converted to booleans, so you wouldn't lose much
by being forced to explicitly convert to boolean with something
interface-specific.

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


Re: Implicit conversion to boolean in if and while statements

2012-07-15 Thread Ranting Rick
On Jul 15, 8:51 pm, Chris Angelico  wrote:
> On Mon, Jul 16, 2012 at 11:21 AM, Ranting Rick
>
>  wrote:
> > If HOWEVER we want to "truth test" an object (as in: "if obj") we
> > should be FORCED to use the bool! Why? Because explicit is better than
> > implicit and readability counts if we want to create maintainable code
> > bases!
>
> > if bool(obj) and a==b: # Correct!
> > if obj and a==b:       # Incorrect!
>
> That still doesn't answer the question of what bool(obj) should do if
> obj is not a bool, and why if can't do the exact same thing, since if,
> by definition, is looking for a boolean state selector.
>
> ChrisA

My point is no different than this example:

py> cost = 1.75
py> cost
1.75
py> 'Cost = ' + cost

Traceback (most recent call last):
  File "", line 1, in 
'Cost = ' + cost
TypeError: cannot concatenate 'str' and 'float' objects
py> 'Cost = ' + str(cost)
'Cost = 1.75'

We DON'T want Python to silently convert "cost" to a string. What we
DO want is to force the author to use the str function thereby making
the conversion explicit.

Same with converting objects to bools.

We DON'T want "if" to magically convert a non-boolean into a boolean.
What we DO want is to force the author to use the bool function
thereby making the conversion explicit. By doing so we transform
confusion into comprehension. By doing so we maintain the principals
of readability counts.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Implicit conversion to boolean in if and while statements

2012-07-15 Thread Steven D'Aprano
On Sun, 15 Jul 2012 12:02:37 -0500, Andrew Berg wrote:

> On 7/15/2012 5:56 AM, Steven D'Aprano wrote:
>> 3) Rather than distinguishing "true" from "false", a more useful
>> dichotomy is between "something" and "nothing". Python includes a
>> number of ways of spelling "nothing" of various types, such as:
>> 
>> None, 0, 0.0, '', [], {}, set()
>> 
>> and nearly everything else is "something".
> Okay, I see the value in this, but I don't understand why None has a
> truth value.

And this is exactly the sort of mental confusion that Laura Crichton 
warned about (see the link I included earlier).

Thinking about "truth values" is harmful, since that's arbitrary. That 
way goes to Javascript, PHP, Ruby etc. that seem to arbitrary pick 
whatever things are truthy or falsey according to some random whim, or 
according to some implementation detail that is meaningless outside of 
the implementation, such as Javascript insisting that while false is 
falsey, if you box it in an object it becomes truthy.

It's crap like that which gives duck-typing bools a bad name.

The distinction you should consider is:

- is it something, or nothing?

(relative to the type in question, of course)

Python (at least the built-ins, third-party code can do any old crap they 
want) is consistent in this. Instances which represent something/non-
emptiness are true, those which represent nothing/emptiness are false.

0? That's the int that represents nothing, so it's false.

23.723? That's one of many floats that represents something, so it's true.

'spam'? That's one of many non-empty strings, so it's true.

''? That's an empty string, that it, it contains nothing, so it is false.

None? That represents a lack of a thing, that is, nothing, so it's false.

(Please don't get into a great philosophical debate over whether 
nothingness is itself something. That impressed me when I was 15. But now 
I know about reification: just because we have a name for a concept 
doesn't mean that the concept is something concrete. None is an object, 
but it *represents* the lack of an object.)


> I would expect None to mean "doesn't exist" or "unknown" or
> something like that - e.g., a value of 0 means 0 jelly beans in the jar
> and None means there isn't a jar.

How you interpret some_variable = None depends on what some_variable 
represents. If some_variable represents "number of jelly beans in a jar", 
then that should be 0 if there is no jar.

If you want to create a language with ternary truth values (yes, no, mu) 
or some larger number (yes, no, maybe, mu, contradiction, unknowable, 
...) be my guest. Just do everyone a favour and do some research on the 
large literature on non-boolean logic systems first.


> FWIW, I have, for a reason I forget, gotten into the habit of writing
> "if x is not None" when testing for None. However, I have not been
> writing "if x is True: ..."/"elif x is False: ..."/"else: 'ruh-roh'"
> when testing for True (in cases where a value of True or False makes
> sense, but any other value would not). Should I?

Only if you want people to laugh at you.

If you *genuinely* want to implement Java in Python, then be explicit 
about your type-testing:

if isinstance(x, bool) and x: ...  

or even 

if type(x) is bool and x: ... # disallow subclasses

Otherwise, where do you stop?

if x is True is True is True is True is True is ... 


Or you could just write idiomatic Python code, including duck-typing, and 
that includes duck-typing bools. Why do you care if somebody calls your 
function with flag=1 instead of flag=True?



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


Re: Implicit conversion to boolean in if and while statements

2012-07-15 Thread Ranting Rick
On Jul 15, 9:13 pm, Steven D'Aprano  wrote:

> I have just written a bunch of code with about two dozen examples similar
> to this:
>
> for item in (seq or []):
>     do_something_with(item)
>
> iterates over seq if it is non-empty, or the empty list. Writing it like
> this would be more painful, more complex, less readable and less
> idiomatic:
>
> if seq is not None:
>     for item in seq:
>         do_something_with(item)
>
> not to mention completely unnecessary if you have already checked that
> seq is either None or a sequence, and not some other arbitrary value.

Short circuitry is a powerful tool! But why the heck would your
sequences ever be None? Are you using None as a default? And if so,
why not use an empty sequence instead ([], {}, "")?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Implicit conversion to boolean in if and while statements

2012-07-15 Thread Chris Angelico
On Mon, Jul 16, 2012 at 12:41 PM, Ranting Rick
 wrote:
> On Jul 15, 9:13 pm, Steven D'Aprano  +comp.lang.pyt...@pearwood.info> wrote:
>
>> I have just written a bunch of code with about two dozen examples similar
>> to this:
>>
>> for item in (seq or []):
>> do_something_with(item)
>
> Short circuitry is a powerful tool! But why the heck would your
> sequences ever be None? Are you using None as a default? And if so,
> why not use an empty sequence instead ([], {}, "")?

Function default arguments spring to mind, especially if the list will
be mutated afterwards.

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


Re: Implicit conversion to boolean in if and while statements

2012-07-15 Thread Ranting Rick
On Jul 15, 9:15 pm, Devin Jeanpierre  wrote:

> For example, instead of "if stack:" or "if bool(stack):", we could use
> "if stack.isempty():". This line tells us explicitly that stack is a
> container. Or instead of "if dist:" or "if bool(dist):" we could use
> "if dist == 0:". This tells us explicitly that stack is a number.
> Supposedly this makes it easier to read code. It certainly reads more
> like English! :)

Yes, but this approach involves adding new "value testing" methods to
every object.

Whilst these specific methods would probably inject more comprehension
than using bool, i believe the bool function can handle this problem
better due to its monolithic and generic nature. No need to memorize
which method is needed for strings, or integers, or lists, etc... just
use bool and everything works. As for the semantics, we should let the
object decide how to respond to a __bool__() request.

But what's the point of having a bool function if we refuse to use it
correctly? We force str, int, and float conversion all day, but not
the bool? Where is the consistency? Where is the bool!?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Implicit conversion to boolean in if and while statements

2012-07-15 Thread Steven D'Aprano
On Sun, 15 Jul 2012 18:21:06 -0700, Ranting Rick wrote:

> If HOWEVER we want to "truth test" an object (as in: "if obj") we should
> be FORCED to use the bool! Why? Because explicit is better than implicit

And this is why Rick always writes code like:

integer_value_three = int(1) + int(2)
assert (int(integer_value_three) == \
int(3) is True) is True, str("arithmetic failed")
list_containing_three_values_which_are_all_integers_but_might_later_have_more_or_fewer_values_or_other_types
 = list([1, 2, integer_value_three])

because you can never have too much explicitness. Who wouldn't want
to read code like that?


> and readability counts if we want to create maintainable code bases!

Yes you, Rick, are correct, that is to say not wrong, that readability, 
that is to say the quality of ease of reading the text in question, 
counts, that is to say that it matters to people who care about ease of 
reading, when our motivation is to create, that is to say write, 
maintainable code bases, that is to say unified collections of code which 
can have software errors fixed and new features added with relatively 
small amounts of effort on behalf of the human programmer.

And that, the reason given in the sentence above, is the reason that we, 
collectively all programmers, should prefer to be explicit, not merely 
conveying meaning by implication about everything we, collectively all 
programmers, write, including typing, use of speech-recognition software, 
or any future technological process by which text or program code or both 
is transcribed from the idea of the human person to a permanent form 
recorded where other people, or non-human sentient beings, can read or 
otherwise gain access to it for the purpose of understanding the content 
of the test or program code or both.


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


Re: Implicit conversion to boolean in if and while statements

2012-07-15 Thread Chris Angelico
On Mon, Jul 16, 2012 at 12:58 PM, Steven D'Aprano
 wrote:
> And that, the reason given in the sentence above, is the reason that we,
> collectively all programmers, should prefer to be explicit, not merely
> conveying meaning by implication about everything we, collectively all
> programmers, write, including typing, use of speech-recognition software,
> or any future technological process by which text or program code or both
> is transcribed from the idea of the human person to a permanent form
> recorded where other people, or non-human sentient beings, can read or
> otherwise gain access to it for the purpose of understanding the content
> of the test or program code or both.

I'd rather be booled in oil.

ChrisA
*ducks for cover*
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Implicit conversion to boolean in if and while statements

2012-07-15 Thread Ranting Rick
On Jul 15, 9:58 pm, Steven D'Aprano  wrote:
> On Sun, 15 Jul 2012 18:21:06 -0700, Ranting Rick wrote:
> > If HOWEVER we want to "truth test" an object (as in: "if obj") we should
> > be FORCED to use the bool! Why? Because explicit is better than implicit
>
> And this is why Rick always writes code like:
...

Traceback (most recent quip last):
  Author: "", line 7, in 
LogicalFallacyError: "Reductio ad absurdum"

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


Re: Implicit conversion to boolean in if and while statements

2012-07-15 Thread Steven D'Aprano
On Sun, 15 Jul 2012 22:15:13 -0400, Devin Jeanpierre wrote:

> For example, instead of "if stack:" or "if bool(stack):", we could use
> "if stack.isempty():". This line tells us explicitly that stack is a
> container. 

isempty is not a container method.

py> container = []
py> container.isempty()
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'list' object has no attribute 'isempty'

Your code tells us explicitly that stack is expected to be an object with 
an isempty() method. What does that mean? Who knows?

calories = macdonalds.fries('large')
calories.isempty()
=> returns True



When you want to write polymorphic code to handle your stack, you end up 
doing something like this:

if isinstance(stack, MyStackClass):
flag = stack.isempty()
else: 
try:
# list, collections.deque, many others
flag = len(stack) == 0
except AttributeError:
try:
if sys.version < '3':
flag = not stack.__nonzero__()
else:
flag = not stack.__bool__()
except AttributeError:
# Is this even possible in Python 3?
flag = False  # I guess...
# If we get here, flag is true if stack is empty.
if flag:
...

Yeah, explicit is *so much better* for readability. Can't you just *feel* 
how much more readable all those irrelevant implementation details are?

If you're smart, you wrap all of the above in a function:

def isempty(stack):
# blah blah as above


But if you're *really* smart, you write to the interface and let Python 
take care of the polymorphic details for you:

if not stack:
...


(Assuming that stack defines __nonzero__ or __len__ correctly, which it 
better if it claims to be a container.)

It boggles my mind that people who are perfectly happy to program to an 
interface or protocol when it comes to (say) iterables, numbers or even 
big complex classes with dozens of methods, suddenly freak out at the 
thought that you can say "if obj" and obj is duck-typed.

There's a distinct lack of concrete, actual problems from duck-typing 
bools, and a heavy over-abundance of strongly-held opinion that such a 
thing is self-evidently wrong.


> As far as I know, the only use of having a polymorphic boolean
> conversion is reducing the amount of typing we do.

The same could be said about *every* polymorphic function.

The benefit is not just because you don't wear out your keyboard as fast. 
The benefit is the same for all other polymorphic code: it lets you write 
better code faster with fewer bugs and less need for unnecessary type 
restrictions.

If there are a few corner cases where you actually *need* to restrict the 
type of your flags to a actual bool, well, Python gives you the tools to 
do so. Just as you can restrict the type of a sequence to exactly a list 
and nothing else, or a number as exactly a float and nothing else. Just 
do your type tests before you start operating on the object, and reject 
anything that doesn't match what you want.

But that should be the exception, not the rule.


> Generally objects
> with otherwise different interfaces are not interchangeable just because
> they can be converted to booleans, so you wouldn't lose much by being
> forced to explicitly convert to boolean with something
> interface-specific.

Until somebody writes an awesomely fast stack class in C and gives it an 
is_empty() method instead of isempty, and your code can't use it because 
you made unnecessary assumptions about the implementation.



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


Re: Implicit conversion to boolean in if and while statements

2012-07-15 Thread Ranting Rick
On Jul 15, 11:03 pm, Steven D'Aprano  wrote:
> On Sun, 15 Jul 2012 22:15:13 -0400, Devin Jeanpierre wrote:

> It boggles my mind that people who are perfectly happy to program to an
> interface or protocol when it comes to (say) iterables, numbers or even
> big complex classes with dozens of methods, suddenly freak out at the
> thought that you can say "if obj" and obj is duck-typed.

"if obj" is in essence doing "if bool(obj)" behind the scenes. My
question is: Why hide such valuable information from the reader? It's
obvious that "if bool(obj)" will return a boolean; whereas "if obj" is
ambiguous.

> There's a distinct lack of concrete, actual problems from duck-typing
> bools, and a heavy over-abundance of strongly-held opinion that such a
> thing is self-evidently wrong.

If the multitudes of misunderstandings from "if obj" on this list have
not convinced you yet, then i lack the energy to educate you!

> > As far as I know, the only use of having a polymorphic boolean
> > conversion is reducing the amount of typing we do.
>
> The same could be said about *every* polymorphic function.

For which "bool" IS!

Wikipedia to the rescue:
"""In computer science, polymorphism is a programming language feature
that allows values of different data types to be handled using a
uniform interface. The concept of parametric polymorphism applies to
both data types and functions. A function that can evaluate to or be
applied to values of different types is known as a polymorphic
function."""

bool("a") -> True
bool(0) -> False
bool([1,2,3]) -> True
bool(True) -> True

> The benefit is not just because you don't wear out your keyboard as fast.
> The benefit is the same for all other polymorphic code: it lets you write
> better code faster with fewer bugs and less need for unnecessary type
> restrictions.

There are NO type restrictions for bool.

> If there are a few corner cases where you actually *need* to restrict the
> type of your flags to a actual bool, well, Python gives you the tools to
> do so.

Yes, the bool()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Implicit conversion to boolean in if and while statements

2012-07-15 Thread Ranting Rick
On Jul 15, 11:20 pm, Steven D'Aprano  wrote:

> (It's not like explicit and implicit are distinct -- everything depends
> on something implicit, if only the meaning of the words you use to
> describe it.)
>
> It certainly doesn't mean that the semantics of Python the language must
> be written out explicitly every time you use each feature.

Of course not. Don't be ridiculous.

> for x in sequence: [...]

This syntax is explicit *enough*. We don't need to be any more
explicit.

But if you are going to argue that "if obj" is *explicit enough*, then
apply your argument consistently to "String"+1.75 also. Why must we be
explicit about string conversion BUT not boolean conversion? Can you
reduce this to the absurd? Or will you just choose to ignore this
valid point?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Implicit conversion to boolean in if and while statements

2012-07-15 Thread Chris Angelico
On Mon, Jul 16, 2012 at 2:53 PM, Ranting Rick
 wrote:
> "if obj" is in essence doing "if bool(obj)" behind the scenes. My
> question is: Why hide such valuable information from the reader? It's
> obvious that "if bool(obj)" will return a boolean; whereas "if obj" is
> ambiguous.

Proves nothing. At least when there are less names used, there's less
possibility of monkey-patching.

>>> def bool(n):
... return 5
...
>>> if bool([]):
... print("Yay?")
...
Yay?

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


Re: Implicit conversion to boolean in if and while statements

2012-07-15 Thread Chris Angelico
On Mon, Jul 16, 2012 at 3:03 PM, Ranting Rick
 wrote:
> But if you are going to argue that "if obj" is *explicit enough*, then
> apply your argument consistently to "String"+1.75 also. Why must we be
> explicit about string conversion BUT not boolean conversion? Can you
> reduce this to the absurd? Or will you just choose to ignore this
> valid point?

Personally, I'm quite okay with automatic upcasts to string. But if
you want to be explicit, particularly with floats, the solution often
is not to use str(), but a proper number-formatting routine. You want
"String%f"%1.75 for full power.

But when you're just letting the language do the translation, it's
much of a muchness whether you put an explicit toString() call in.

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


Re: Implicit conversion to boolean in if and while statements

2012-07-15 Thread Mark Lawrence

On 16/07/2012 04:05, Chris Angelico wrote:

On Mon, Jul 16, 2012 at 12:58 PM, Steven D'Aprano
 wrote:

And that, the reason given in the sentence above, is the reason that we,
collectively all programmers, should prefer to be explicit, not merely
conveying meaning by implication about everything we, collectively all
programmers, write, including typing, use of speech-recognition software,
or any future technological process by which text or program code or both
is transcribed from the idea of the human person to a permanent form
recorded where other people, or non-human sentient beings, can read or
otherwise gain access to it for the purpose of understanding the content
of the test or program code or both.


I'd rather be booled in oil.

ChrisA
*ducks for cover*



What a silly bunt[1] :)
*also ducks for cover*

[1] from a Monty Python sketch for those who don't know about a guy who 
pronounces c's as b's, hence Kings Bollege Bambridge


--
Cheers.

Mark Lawrence.



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