Re: Implicit conversion to boolean in if and while statements

2012-07-16 Thread Steven D'Aprano
On Tue, 17 Jul 2012 00:18:28 -0400, Devin Jeanpierre wrote:

> On Mon, Jul 16, 2012 at 12:03 AM, Steven D'Aprano
>  wrote:
>> 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.
> 
> Your entire reply is predicated on this idea that I was talking about
> writing classes with this extra "isempty" method.
> 
> No. I was talking about having "isempty" be part of the collection
> interface, and eliminating polymorphic bool conversion.

It already is part of the collection interface: it is spelled __nonzero__ 
(Python 2) or __bool__ (Python 3), and like all dunder methods, it is 
called automatically for you when you use the right syntax:

# do this
x = n - len(y)
if x and y:
...

# don't do this
x = n.__sub__(y.__len__())
if x.__nonzero__() and y.__nonzero__():
...


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


Re: Implicit conversion to boolean in if and while statements

2012-07-16 Thread Steven D'Aprano
On Mon, 16 Jul 2012 11:13:33 -0700, Ethan Furman wrote:

> Steven D'Aprano wrote:
>> 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").
> 
> --> import datetime
> --> mn = datetime.time(0)
> --> mn
> datetime.time(0, 0)
> --> mn == 0
> False
> 
> Apparently, midnight does not equal zero.

My mistake.



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


Re: Implicit conversion to boolean in if and while statements

2012-07-16 Thread Andrew Berg
On 7/16/2012 11:39 PM, Steven D'Aprano wrote:
> If you need three (or four, or fifty) 
> distinguishable states, then obviously boolean context will not solve 
> your problem. I never said it would.
That is the impression I got from this statement:

> 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.
But I guess you misunderstood (or were just picking at) the example.

Of course I can (and do) explicitly use "if x is not None" when testing
for None, but I don't want a bug being obscured because "if x" accepts
an erroneous value that it interprets as truthy or falsey. I could be
explicit when testing for things other than None, but apparently that's
un-Pythonic.

To put it in duck-typing terms, why should everything have to quack like
True or False? Sure, I can see why 1 quacks like True or [] quacks like
False, but I don't see why say, a Logger or function should quack like
either. Should a Thread object be True if it's been started and False
otherwise?

If it truly is about something vs. nothing, why is a NameError (or
AttributeError) raised when testing with an undefined variable? Being
undefined quacks like nothing, doesn't it?
-- 
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-16 Thread Andrew Berg
On 7/16/2012 11:11 PM, Steven D'Aprano wrote:
> If you are right that SimpleNamespace should be treated as a container, 
> then it should implement container semantics. Since it doesn't, that is 
> either:
> 
> 1) a bug; or
> 2) a triumph of laziness over correctness
> 
> I imagine though that the Python dev's answer will basically be #2: "it 
> isn't a container, it just behaves a little bit like a container, except 
> when it doesn't" kinda thing. But feel free to report it as a bug and see 
> what happens.
I'm not saying it's necessarily wrong, but I do think it quacks a lot
like a container, even though it isn't one, especially if you're
listening for quacks instead of looking for ducks.
-- 
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-16 Thread Steven D'Aprano
On Mon, 16 Jul 2012 20:57:43 -0500, Andrew Berg wrote:

> I have a better real example, but I opted not to use it before since it
> requires some explanation - IRC messages. A client-to-server message has
> the basic form of b'COMMAND arguments :message' (e.g. b'PRIVMSG #channel
> :hi guys!'). Some commands have no message part because there is no
> message associated with it (e.g. b'JOIN #channel') and there is at least
> one where there is a big difference between a blank message (b'') and no
> message - b'TOPIC #channel' is a request for the topic while b'TOPIC
> #channel :' clears the topic since the part after the b':' is b''
> (b'TOPIC #channel :Welcome to #channel' sets the topic to "Welcome to
> #channel"). 

Okay, so you have two distinct "nothing" states when considering the 
message part of an IRC command: the empty string, and missing.

That's okay. Floats have two zeroes (+0.0 and -0.0); complex numbers have 
four. (Although they try hard to hide that distinction from you.)

There's nothing that says that you can only have a single falsey value in 
a type, or that you might not sometimes wish to distinguish between 
different false-like states. You need to distinguish between the many 
different true-like messages, so you should not be surprised that you 
need to distinguish between two false-like messages.

There are many ways to implement this. Here are just the most obvious:

1) a Command object where the message attribute is optional, but if
   present, it is always a string;

2) a Command object where the message attribute is always present, but
   can be a string or some non-string sentinel value (e.g. None);

3) a string, where the message attribute is determined by the location
   of the colon, if any

4) a tuple with either two or three fields: (command, channel [,message])



> In my code, I would have an object representing a message
> rather than parsing it multiple times. If the message
> attribute is not None, I send b'{command} {args} :{message}', otherwise
> b'{command} {args}'. 

Clear and obvious. Nothing wrong with that.


> I could do:
> 
> if has_message:
>   send('{command} {args} :{message}')
> else:
>   send('{command} {args}')
> 
> but then I'd have to make sure has_message stays accurate since message
> won't necessarily be. 

Yes, keeping a separate variable is a mug's game. Encapsulate it in the 
Command object, and have the Command object responsible for keeping it in 
sync (assuming it is mutable), or just make Command immutable and be done 
with it.


> Or maybe I could leave message undefined and catch
> the appropriate exception. However, using None is the cleanest and most
> obvious.

Yes it is. What's your point?

You've discovered a real-world situation where you can't collapse the 
entire universe of valid values into just two, True and False, without 
losing information. Did you think that this would be surprising?

Python developers often talk about interpreting objects "in a boolean 
context" -- that's a pretty big hint that the semantics are to collapse 
the value into two states. If you need three (or four, or fifty) 
distinguishable states, then obviously boolean context will not solve 
your problem. I never said it would.



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


Re: Implicit conversion to boolean in if and while statements

2012-07-16 Thread Chris Angelico
On Tue, Jul 17, 2012 at 2:18 PM, Ranting Rick
 wrote:
> On Jul 16, 11:11 pm, Steven D'Aprano  +comp.lang.pyt...@pearwood.info> wrote:
>
>> I imagine though that the Python dev's answer will basically be #2: "it
>> isn't a container, it just behaves a little bit like a container, except
>> when it doesn't" kinda thing.
>
> The emperor has no clothes!

The Troll's New Point.

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


Re: Implicit conversion to boolean in if and while statements

2012-07-16 Thread Devin Jeanpierre
On Mon, Jul 16, 2012 at 12:03 AM, Steven D'Aprano
 wrote:
> 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.

Your entire reply is predicated on this idea that I was talking about
writing classes with this extra "isempty" method.

No. I was talking about having "isempty" be part of the collection
interface, and eliminating polymorphic bool conversion.

If you were confused, instead of assuming I meant something patently
absurd, you should have asked for a clarification.

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


Re: Implicit conversion to boolean in if and while statements

2012-07-16 Thread Steven D'Aprano
On Mon, 16 Jul 2012 20:22:18 -0500, Andrew Berg wrote:

> On 7/15/2012 3:28 PM, Terry Reedy wrote:
>> Because everything does (or should).
> I can see how truth testing for empty values is convenient, but perhaps
> objects should only have a truth value if explicitly given one -
> particularly in cases where such a value wouldn't be obvious or the
> obvious value isn't the actual one:

You have run into Python's default behaviour: objects are treated as 
something by default. If you want them to represent nothing, you have to 
explicitly code that case.

py> o = object()
py> bool(o)
True

Yet again, thinking about something versus nothing instead of true/false 
makes the behaviour both obvious and correct: of course an object should 
be treated as something (true-like) rather than nothing (false-like) by 
default, it's an *object* is it not?

If you want your type to implement non-default semantics, such as 
container semantics, then you need to code it.


 c = types.SimpleNamespace()
 if c: print('c')
> ...
> c
 c.__dict__
> {}
> 
> Would it not be reasonable to expect an empty namespace to have a truth
> value of False since [] and friends do? It's a bit of a gray area for an
> object defined by "class C: pass", but this is *specifically intended*
> to be a namespace. Why should things like functions or exceptions have
> truth values?

And this is a good life-lesson that any class called "SimpleFoo" will not 
stay simple for long.

If you are right that SimpleNamespace should be treated as a container, 
then it should implement container semantics. Since it doesn't, that is 
either:

1) a bug; or
2) a triumph of laziness over correctness

I imagine though that the Python dev's answer will basically be #2: "it 
isn't a container, it just behaves a little bit like a container, except 
when it doesn't" kinda thing. But feel free to report it as a bug and see 
what happens.

(This is not *entirely* wrong, because SimpleNamespace certainly doesn't 
*claim* to be a container, nor does it expose the full container API. But 
it should, even if that means it is no longer quite so simple.)



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


Re: Implicit conversion to boolean in if and while statements

2012-07-16 Thread Chris Angelico
On Tue, Jul 17, 2012 at 11:57 AM, Andrew Berg  wrote:
> I could do:
>
> if has_message:
> send('{command} {args} :{message}')
> else:
> send('{command} {args}')
>
> but then I'd have to make sure has_message stays accurate since message
> won't necessarily be. Or maybe I could leave message undefined and catch
> the appropriate exception. However, using None is the cleanest and most
> obvious.
>
> I know Rick likes to troll, but I do agree with him that "if something:"
> for arbitrary objects can be ambiguous or confusing. I don't think
> if/while must have True or False, but not every object has an obvious
> truth value.

Using None when '' is a valid token is the right thing to do (see
also, for instance, SQL's NULL, which is often used the same way). And
then you have gone away from the language's idea of whether a string
is truthy or not, so you get explicit:

if message is not None:
   send('{command} {args} :{message}')

Easy! Or if the language went the other way ("all strings are true"),
it would be the other way around, you'd use "if message!=''" for the
other case. It's not a difficult problem.

Carry on bikeshedding. :)

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


Re: Implicit conversion to boolean in if and while statements

2012-07-16 Thread Andrew Berg
On 7/16/2012 7:43 PM, Steven D'Aprano wrote:
> The existence of a jar or no jar is irrelevant to the question of how 
> many jellybeans there are. They are two different things, and therefore 
> need two different values. There are many ways to implement this.
I have a better real example, but I opted not to use it before since it
requires some explanation - IRC messages.
A client-to-server message has the basic form of b'COMMAND arguments
:message' (e.g. b'PRIVMSG #channel :hi guys!'). Some commands have no
message part because there is no message associated with it (e.g. b'JOIN
#channel') and there is at least one where there is a big difference
between a blank message (b'') and no message - b'TOPIC #channel' is a
request for the topic while b'TOPIC #channel :' clears the topic since
the part after the b':' is b'' (b'TOPIC #channel :Welcome to #channel'
sets the topic to "Welcome to #channel"). In my code, I would have an
object representing a message rather than parsing it multiple times. If
the message
attribute is not None, I send b'{command} {args} :{message}', otherwise
b'{command} {args}'. If I considered '' falsey, either I would require
all messages to have ":" (which would not actually be part of the
message) or have any request to view the topic as a channel op clear the
topic. This would apply to the server parsing the message as well. A few
other commands have messages optional as well, but they are not as
serious as TOPIC.

I could do:

if has_message:
send('{command} {args} :{message}')
else:
send('{command} {args}')

but then I'd have to make sure has_message stays accurate since message
won't necessarily be. Or maybe I could leave message undefined and catch
the appropriate exception. However, using None is the cleanest and most
obvious.

I know Rick likes to troll, but I do agree with him that "if something:"
for arbitrary objects can be ambiguous or confusing. I don't think
if/while must have True or False, but not every object has an obvious
truth value.
-- 
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-16 Thread rusi
On Jul 15, 9:50 pm, Rick Johnson  wrote:
> 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.

If you know some English, its clear that if and while create bool
contexts.
[If you know English but have not studied logic the 'if/while' make
sense whereas 'bool' is gobbledygook]

The issue is not where the cast goes to -- this clearly is bool
But where the cast comes from -- which requires tracing program-paths
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Implicit conversion to boolean in if and while statements

2012-07-16 Thread Andrew Berg
On 7/15/2012 3:28 PM, Terry Reedy wrote:
> Because everything does (or should).
I can see how truth testing for empty values is convenient, but perhaps
objects should only have a truth value if explicitly given one -
particularly in cases where such a value wouldn't be obvious or the
obvious value isn't the actual one:

>>> c = types.SimpleNamespace()
>>> if c: print('c')
...
c
>>> c.__dict__
{}

Would it not be reasonable to expect an empty namespace to have a truth
value of False since [] and friends do? It's a bit of a gray area for an
object defined by "class C: pass", but this is *specifically intended*
to be a namespace. Why should things like functions or exceptions have
truth values?

Note: For those who aren't aware, types.SimpleNamespace was added in
3.3.0b1.

On a side note, I tend to do this:

x = some_list
try:
y = x.pop()
except IndexError:
do_something_else()

rather than:

if x:
y = x.pop()
else:
do_something_else()

but of course that only applies to empty lists/sets/related and not
0/0.0/None and only when I want something from the list/set/whatever.
-- 
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-16 Thread Steven D'Aprano
On Mon, 16 Jul 2012 13:28:14 -0400, Dennis Lee Bieber wrote:

> On 16 Jul 2012 02:38:35 GMT, Steven D'Aprano
>  declaimed the following in
> gmane.comp.python.general:
> 
>> On Sun, 15 Jul 2012 12:02:37 -0500, Andrew Berg wrote:
>> 
>> 
>> > 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).
>>
>>
>   Would one rather have the behavior seen in SQL for Null?
> http://www.firebirdsql.org/file/documentation/reference_manuals/
user_manuals/Firebird-Null-Guide.pdf


That's a 51 page document. I'm not sure I know which behaviour you are 
referring to.

Seems to me that the Firebird NULL object is closer to a float NaN than 
to Python's None, except that Firebird treats comparisons with NULL as 
returning a NULL, while Python treats comparisons with NaN as True or 
False.

Both behaviours are reasonable, but the Firebird behaviour seems to be 
more error-prone.


>   Hey, let's turn the IF statement into tri-state logic...
[...]

I'm not sure if you're being sarcastic here or not. Ternary logic is 
perfectly reasonable, although I expect that it would be error-prone 
because programmers would forget the "unknown" clause all the time. It 
looks like Firebird implements the variety of ternary logical called 
"Keene logic".

Of course, ternary logic can always be re-written in binary terms. 
Assuming that UNKNOWN evaluates as false:

if flag:
true-clause
else:
if flag is UNKNOWN:
unknown-clause
else:
false-clause



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


Re: Implicit conversion to boolean in if and while statements

2012-07-16 Thread Steven D'Aprano
On Tue, 17 Jul 2012 01:12:47 +, Steven D'Aprano wrote:

> It
> looks like Firebird implements the variety of ternary logical called
> "Keene logic".

Oops, I meant "Kleene".



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


Re: Implicit conversion to boolean in if and while statements

2012-07-16 Thread Steven D'Aprano
On Mon, 16 Jul 2012 13:54:32 -0700, Ethan Furman wrote:

> Andrew Berg wrote:
>> On 7/15/2012 9:38 PM, Steven D'Aprano wrote:
 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.
>  >
>> What is None supposed to mean then, and what should I do when I have to
>> make a distinction between "doesn't exist" and "empty"? Sure, if I need
>> to count the total number of jelly beans in all my stores, the
>> distinction is meaningless, but if I need to find out which stores sell
>> jelly beans so I know which stores need to be restocked, the
>> distinction is quite important.
> 
> I'm not sure what Steven was trying to say there, but for me:
> 
> jar with no jellybeans == 0
> 
> no jar == None

The existence of a jar or no jar is irrelevant to the question of how 
many jellybeans there are. They are two different things, and therefore 
need two different values. There are many ways to implement this.

# One way
jar_exists = True  # or possibly False
jellybeans = 42  # or whatever the number is, possibly 0

# Another way
jar = Jar(number_of_beans=jellybeans) if jar_exists else None
jellybeans = jar.jellybeans if jar is not None else 0

If you have many jars, and you want to count the total number of 
jellybeans:

total = sum(jar.jellybeans for jar in jars if jar is not None)


Strictly speaking, the "is not None" is redundant, but it expresses the 
intent better than the alternative. Assuming that jar instances follow 
the standard Python API for containers, and is treated as falsey when it 
has a jellybean count of zero:

total = sum(jar.jellybeans for jar in jars if jar)
  # relies on the fact that adding zero to a number makes 
  # no difference, so you can safely leave zeroes out


Here's a case where you *must* distinguish between empty jars and None:

number_of_jars = sum(1 for jar in jars if jar is not None)

and a case where you *shouldn't*:

number_of_nonempty_jars = sum(1 for jar in jars if jar)

Of course you can write this:

number_of_nonempty_jars = sum(
1 for jar in jars if jar is not None and jar.jellybeans > 1
)

but that overwhelms the code with incidental implementation details about 
jellybean counts, which is prone to bugs. (Did you spot it?)

Even jar.isempty() would be better, but better still is to *not* invent 
your own container API but to use the standard Python one instead and 
define an appropriate __nonzero__ (Python 2) or __bool__ (Python 3) 
method.

If I insist on making a single object do duty for both the jar and the 
jellybean count, then I need a "null jar object", and I probably end up 
with something like this:

Jar(number_of_beans=None) => null jar object with jar.jellybeans = 0
Jar(number_of_beans=0) => normal jar object with jar.jellybeans = 0
Jar(number_of_beans=42) => normal jar object with jar.jellybeans = 42

and then my code becomes even more complicated and less understandable, 
but hey, it's *my* code and I can do whatever damn-fool thing I like!


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


Re: Diagramming code

2012-07-16 Thread Andrew Cooper
On 16/07/2012 21:41, Andrea Crotti wrote:
> On 07/16/2012 02:26 AM, hamilton wrote:
>> Is there any software to help understand python code ?
>>
>> Thanks
>>
>> hamilton
> 
> Sometimes to get some nice graphs I use gprof2dot
> (http://code.google.com/p/jrfonseca/wiki/Gprof2Dot)
> or doxygen (http://www.stack.nl/~dimitri/doxygen/)
> 
> gprof2dot analyses the output of the profiling that you get running the
> code through the python profiler,
> doing for example:
> 
> python -m cProfile -o $STATS $FNAME $@
> $GPROF2DOT -f pstats $STATS | dot -T$TYPE -o $OUT
> 
> doxygen is more useful for C++ but it's also able to infer a few things
> (without running) from a python project..

+1 for doxygen.

Combined with http://code.foosel.org/doxypy , it is a fully featured
solution.  I use it for all my projects, python and otherwise.

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


Re: Style question: metaclass self vs cls?

2012-07-16 Thread Terry Reedy

On 7/16/2012 11:29 AM, Steven D'Aprano wrote:

Here's a style question for you: in a metaclass, what should I call the
instance parameter of methods, "cls" or "self"?

class ExampleMeta(type):
 def method(self, *args): ...

I'm not quite sure if that feels right. On the one hand, self is the
ExampleMeta instance alright... but on the other, self is actually a
class, so I feel I want to call it "cls" rather than "self", which makes
it more obvious that you're looking at a metaclass.


I have never seriously written a metaclass, but as a reader I would 
prefer 'cls'.



On the third-hand, it may be confusing that the argument is called "cls"
but not decorated with classdecorator.


To me, that reinforces 'looking as a metaclass'.

An @classmethod in a class is a class method specific to the particular 
class. A method in a metaclass is a method common to all classes of the 
metaclass. They could be written differently, yet calling the first 
param 'cls' either way seems reasonable.



I'm very slightly leaning towards writing metaclasses like this:

class ExampleMeta(type):
 def __new__(meta, *args): ...
 def method(cls, *args): ...

class Example(metaclass=ExampleMeta):
 def another_method(self): ...



What do others do?


Not too many people write real metaclasses. Python lets you chose. Have 
you looked at the C code of type? (Not that you are bound by it.)


--
Terry Jan Reedy



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


Re: No more Python support in NetBeans 7.0

2012-07-16 Thread trevor . carlston
On Wednesday, October 26, 2011 8:06:16 PM UTC-6, w...@naveed.net wrote:
> Sorry to comment on an old topic, but I wanted to clarify for others like me 
> who might get the wrong idea. 
> 
> It looks like this is no longer true. Netbeans 7 might be supporting python 
> after all.
> 
> http://wiki.netbeans.org/Python70Roadmap

I checked the date on that document it's last update was  5 November 2009
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Implicit conversion to boolean in if and while statements

2012-07-16 Thread Laszlo Nagy



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?
Not all decisions in Python are based purely on the "explicit enough" 
thing. Some things in the language cannot be explained using 
explicitness alone. So, when we cannot fully explain the ' why 
String+1.75 ' question with statements about explicitness then it 
doesn't mean that anybody lied or wrote something wrong. :-)



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


Re: No more Python support in NetBeans 7.0

2012-07-16 Thread trevor . carlston
On Wednesday, October 26, 2011 8:06:16 PM UTC-6, w...@naveed.net wrote:
> Sorry to comment on an old topic, but I wanted to clarify for others like me 
> who might get the wrong idea. 
> 
> It looks like this is no longer true. Netbeans 7 might be supporting python 
> after all.
> 
> http://wiki.netbeans.org/Python70Roadmap

This article is dated January 29th of 2011
http://netbeans.org/projects/www/lists/nbpython-dev/archive/2011-01/message/0
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Implicit conversion to boolean in if and while statements

2012-07-16 Thread Laszlo Nagy



...

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


Deary deary me Rick. Reductio ad adsurdum is not a fallacy. It is a
counter-argument to an argument or claim, by showing that the premise of
the original claim leads to an absurd conclusion.

You have claimed that we should always be explicit whenever we write. But
you do not actually live up to your own advice, because you can't: it is
absurd to try to be explicit about everything all the time. You have
misunderstood the purpose of the Zen of Python: it is not to claim that
everything should be explicit, but to avoid code that is hard to
understand because things which need to be explicit for clarity are
implied by other parts of your code.


I agree. There is no pont in abolutizing explicitness anyway. It is not 
a yes/no question. You cannot tell that somebody is "not explicit". It 
is not something that can be decided. But you can say that he was "not 
explicit enough" in a concrete case. There is an accepted level of 
explicitness. You can probably always be more expicit, or less explicit. 
Being more explicit is not the goal. But is a good practice to be more 
explicit if it helps you achieve the real goal. For example, writting a 
program that can be maintained easily.


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


Re: Implicit conversion to boolean in if and while statements

2012-07-16 Thread Ethan Furman

Andrew Berg wrote:

On 7/15/2012 9:38 PM, Steven D'Aprano wrote:

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.

>

What is None supposed to mean then, and what should I do when I have to
make a distinction between "doesn't exist" and "empty"? Sure, if I need
to count the total number of jelly beans in all my stores, the
distinction is meaningless, but if I need to find out which stores sell
jelly beans so I know which stores need to be restocked, the distinction
is quite important.


I'm not sure what Steven was trying to say there, but for me:

jar with no jellybeans == 0

no jar == None

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


Re: Diagramming code

2012-07-16 Thread Andrea Crotti

On 07/16/2012 02:26 AM, hamilton wrote:

Is there any software to help understand python code ?

Thanks

hamilton


Sometimes to get some nice graphs I use gprof2dot 
(http://code.google.com/p/jrfonseca/wiki/Gprof2Dot)

or doxygen (http://www.stack.nl/~dimitri/doxygen/)

gprof2dot analyses the output of the profiling that you get running the 
code through the python profiler,

doing for example:

python -m cProfile -o $STATS $FNAME $@
$GPROF2DOT -f pstats $STATS | dot -T$TYPE -o $OUT

doxygen is more useful for C++ but it's also able to infer a few things 
(without running) from a python project..

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


Re: Implicit conversion to boolean in if and while statements

2012-07-16 Thread Andrew Berg
On 7/15/2012 9:38 PM, Steven D'Aprano wrote:
>> 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.
What is None supposed to mean then, and what should I do when I have to
make a distinction between "doesn't exist" and "empty"? Sure, if I need
to count the total number of jelly beans in all my stores, the
distinction is meaningless, but if I need to find out which stores sell
jelly beans so I know which stores need to be restocked, the distinction
is quite important.
-- 
CPython 3.3.0b1 | Windows NT 6.1.7601.17803
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Re: PyQt QCalendarWidget events question

2012-07-16 Thread John Posner
On 7/16/2012 12:28 PM, tinn...@isbd.co.uk wrote:
> tinn...@isbd.co.uk wrote:
>> I am trying to use the PyQt4 calendar widget to perform some different
>> actions on specific dates.  There are three events available:-
>>
>> selectionChanged()
>> activated(QDate)
>> clicked(QDate)
>>
>> On trying all these out it would appear that the event handlers get
>> called as follows:-
>>
>> The clicked(QDate) event gets called if you click on an already
>> selected date.
>>
>> The selectionChanged() and then the clicked(QDate) events are
>> called when you click on a new date.
>>
>> The selectionChanged(), then the clicked(QDate) and then the
>> activated(QDate) events are called if you double-click on a new date.
>>
>> The clicked(QDate) and then the activated(QDate) events are called
>> if you double-click on an already selected date.
>>
>>
>> How can I get a single-click on a date to get 'Action1' and double-click
>> on a date to get 'Action2'?
> I'm sorry, this got sent a bit before I'd completed it.  The trouble
> is that I want to run Action1 if I single-click on a date whether or
> not it's a changed date and I want to run Action2 if I double-click on
> a date whether or not it's a changed date.  However I don't see how I
> can do this because of the order in which the event handlers are
> called.
>
> Is there any way to manipulate this so I can get the result I want? 
> At the moment the only way I can see to do it is to wait a while after
> a click and then look at what actions occurred but this seems a real
> bodge.

I suspect that the consensus would be "don't do that" -- having
single-click and double click perform unrelated actions. But here's an
implementation based on the advice at
http://www.qtcentre.org/threads/7858-Double-Click-Capturing

(use Ctrl-Break to break out of the event loop)

import PyQt4.QtCore as C
import PyQt4.QtGui as G

class Button(G.QPushButton):
def __init__(self, text):
G.QPushButton.__init__(self, text)

# flag to suppress second mouseReleaseEvent
# in this double-click event sequence:
# 1. mousePressEvent
# 2. mouseReleaseEvent
# 3. mouseDoubleClickEvent
# 4. mouseReleaseEvent
self.double_clicked = False

def mouseReleaseEvent(self, evt):
# executed for first mouseReleaseEvent
if not self.double_clicked:
self.first_click_timer = C.QTimer()
self.first_click_timer.setSingleShot(True)
# double-click must occur within 1/4 second of first-click
release
self.first_click_timer.setInterval(250)
self.first_click_timer.timeout.connect(self.single_click_action)
self.first_click_timer.start()
# executed for second mouseReleaseEvent
else:
# reset the flag
self.double_clicked = False

def single_click_action(self):
print "Performing single-click action"

def mouseDoubleClickEvent(self, evt):
# suppress the single-click action; perform double-click action
instead
self.first_click_timer.stop()
print "Performing double-click action"

# prepare for second mouseReleaseEvent
self.double_clicked = True

# main program

app = G.QApplication([])
button = Button("Click or double-click me")
button.show()
app.exec_()


HTH,
John

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


Re: Diagramming code

2012-07-16 Thread Miki Tebeka
> Is there any software to help understand python code ?
For module dependency you can try http://furius.ca/snakefood/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Diagramming code

2012-07-16 Thread hamilton


Thank you Fred.

I am new to python and am reviewing code I find online.

Some projects do have docs that spell out what its doing,
but many projects that I have download have just the code.

I have my own personal style to decypher C and C++ code.

But python is still foreign to me.

hamilton


On 7/16/2012 11:02 AM, Sells, Fred wrote:

You leave many relevant questions unanswered.

1. Is the original developer/team available or have you been left with
the code and little or no doc's?

2. How big is big in terms of the number of files/modules in the
project?

3. Is there a reasonable structure to the project in terms of
directories and a meaningful hierarchy

4. Does the project currently work and you just have to maintain/enhance
it or was it "abandoned" by the original team in an unknown state and
you have to save a sinking ship?

5. Are you an experienced Python programmer or a beginner.

6. Is the original code "pythonic" (i.e. clean and simple with brief,
well organized methods) or do you have functions over 50 lines of code
with multiple nested control statements and meaningless variable names?

7. Is there any documentation that defines what it should do and how it
should do it.  i.e. how do you know when it's working?

These issues are not really Python specific, but if you've been given a
"broken" project that has 200 poorly organized modules and little or no
documentation and no access to the original team, a good first step
would be to update your resume ;)

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

hamilton

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




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


Re: Implicit conversion to boolean in if and while statements

2012-07-16 Thread Ethan Furman

Steven D'Aprano wrote:

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"). 


--> import datetime
--> mn = datetime.time(0)
--> mn
datetime.time(0, 0)
--> mn == 0
False

Apparently, midnight does not equal zero.  Possibly because it should be 
truthy.  ;)


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


Re: assertraises behaviour

2012-07-16 Thread Peter Otten
andrea crotti wrote:

> Good thanks, but there is something that implements this behaviour..
> For example nose runs all the tests, and if there are failures it goes
> on and shows the failed tests only in the end, so I think it is
> possible to achieve somehow, is that correct?

No, I don't see how the code you gave above can fail with an OSError. 

Can you give an example that produces the desired behaviour with nose? Maybe 
we can help you translate it to basic unittest.

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


Re: Implicit conversion to boolean in if and while statements

2012-07-16 Thread Albert van der Horst
In article <50038364$0$29995$c3e8da3$54964...@news.astraweb.com>,
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:
>
>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?

Java programmers?

(Couldn't resist ;-) )

>--
>Steven

Groetjes Albert

--
-- 
Albert van der Horst, UTRECHT,THE NETHERLANDS
Economic growth -- being exponential -- ultimately falters.
albert@spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst

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


Re: Implicit conversion to boolean in if and while statements

2012-07-16 Thread Albert van der Horst
In article ,
Ranting Rick   wrote:

>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.

We do want Python to silently convert "cost" to a string in the
proper context.

cost= 3.75
print( cost )

>
>Same with converting objects to bools.

I think "if" is sufficient context to convert something to a boolean.
It now is a matter of good taste and what fits best in Python as a
whole. Nothing to be dogmatic about.

Groetjes Albert

--
-- 
Albert van der Horst, UTRECHT,THE NETHERLANDS
Economic growth -- being exponential -- ultimately falters.
albert@spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst

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


RE: Diagramming code

2012-07-16 Thread Sells, Fred
You leave many relevant questions unanswered.

1. Is the original developer/team available or have you been left with
the code and little or no doc's?

2. How big is big in terms of the number of files/modules in the
project?  

3. Is there a reasonable structure to the project in terms of
directories and a meaningful hierarchy

4. Does the project currently work and you just have to maintain/enhance
it or was it "abandoned" by the original team in an unknown state and
you have to save a sinking ship?

5. Are you an experienced Python programmer or a beginner.

6. Is the original code "pythonic" (i.e. clean and simple with brief,
well organized methods) or do you have functions over 50 lines of code
with multiple nested control statements and meaningless variable names?

7. Is there any documentation that defines what it should do and how it
should do it.  i.e. how do you know when it's working?

These issues are not really Python specific, but if you've been given a
"broken" project that has 200 poorly organized modules and little or no
documentation and no access to the original team, a good first step
would be to update your resume ;)

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

hamilton

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

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


Re: assertraises behaviour

2012-07-16 Thread andrea crotti
Good thanks, but there is something that implements this behaviour..
For example nose runs all the tests, and if there are failures it goes
on and shows the failed tests only in the end, so I think it is
possible to achieve somehow, is that correct?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyQt QCalendarWidget events question

2012-07-16 Thread tinnews
tinn...@isbd.co.uk wrote:
> I am trying to use the PyQt4 calendar widget to perform some different
> actions on specific dates.  There are three events available:-
> 
> selectionChanged()
> activated(QDate)
> clicked(QDate)
> 
> On trying all these out it would appear that the event handlers get
> called as follows:-
> 
> The clicked(QDate) event gets called if you click on an already
> selected date.
> 
> The selectionChanged() and then the clicked(QDate) events are
> called when you click on a new date.
> 
> The selectionChanged(), then the clicked(QDate) and then the
> activated(QDate) events are called if you double-click on a new date.
> 
> The clicked(QDate) and then the activated(QDate) events are called
> if you double-click on an already selected date.
> 
> 
> How can I get a single-click on a date to get 'Action1' and double-click
> on a date to get 'Action2'?

I'm sorry, this got sent a bit before I'd completed it.  The trouble
is that I want to run Action1 if I single-click on a date whether or
not it's a changed date and I want to run Action2 if I double-click on
a date whether or not it's a changed date.  However I don't see how I
can do this because of the order in which the event handlers are
called.

Is there any way to manipulate this so I can get the result I want? 
At the moment the only way I can see to do it is to wait a while after
a click and then look at what actions occurred but this seems a real
bodge.

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


PyQt QCalendarWidget events question

2012-07-16 Thread tinnews
I am trying to use the PyQt4 calendar widget to perform some different
actions on specific dates.  There are three events available:-

selectionChanged()
activated(QDate)
clicked(QDate)

On trying all these out it would appear that the event handlers get
called as follows:-

The clicked(QDate) event gets called if you click on an already
selected date.

The selectionChanged() and then the clicked(QDate) events are
called when you click on a new date.

The selectionChanged(), then the clicked(QDate) and then the
activated(QDate) events are called if you double-click on a new date.

The clicked(QDate) and then the activated(QDate) events are called
if you double-click on an already selected date.


How can I get a single-click on a date to get 'Action1' and double-click
on a date to get 'Action2'?

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


Style question: metaclass self vs cls?

2012-07-16 Thread Steven D'Aprano
Here's a style question for you: in a metaclass, what should I call the 
instance parameter of methods, "cls" or "self"?

class ExampleMeta(type):
def method(self, *args): ...

I'm not quite sure if that feels right. On the one hand, self is the 
ExampleMeta instance alright... but on the other, self is actually a 
class, so I feel I want to call it "cls" rather than "self", which makes 
it more obvious that you're looking at a metaclass.

On the third-hand, it may be confusing that the argument is called "cls" 
but not decorated with classdecorator.

I'm very slightly leaning towards writing metaclasses like this:

class ExampleMeta(type):
def __new__(meta, *args): ...
def method(cls, *args): ...

class Example(metaclass=ExampleMeta):
def another_method(self): ...


What do others do?



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


Re: assertraises behaviour

2012-07-16 Thread Peter Otten
andrea crotti wrote:

> 2012/7/16 Christian Heimes :
>>
>> The OSError isn't catched as the code never reaches the line with "raise
>> OSError". In other words "raise OSError" is never executed as the
>> exception raised by "assert False" stops the context manager.
>>
>> You should avoid testing more than one line of code in a with
>> self.assertRaises() block.
>>
>> Christian
>>
>> --
>> http://mail.python.org/mailman/listinfo/python-list
> 
> Ok now it's more clear, and normally I only test one thing in the block.
> But I find this quite counter-intuitive, because in the block I want
> to be able to run something that raises the exception I catch (and
> which I'm aware of), but if another exception is raised it *should*
> show it and fail in my opinion..

That doesn't sound like "it's clearer". Perhaps it helps if you translate 
your code into a standard try...except:

>>> class A(Exception): pass
... 
>>> class B(Exception): pass
... 
>>> try:
... raise A
... raise B
... except A as e:
... print "caught %r" % e
... 
caught A()

The try block is left at the "raise A' statement" -- Python doesn't have an 
equivalent of Basic's "resume next". Therefore B (or OSError) is never 
raised.

PS: Strictly speaking your "assert False" is equivalent to 

if __debug__ and False: raise AssertionError

Therefore you *can* trigger the OSError by invoking the interpreter with the
"-O" option:

$ python -c 'assert False; raise OSError'
Traceback (most recent call last):
  File "", line 1, in 
AssertionError
$ python -O -c 'assert False; raise OSError'
Traceback (most recent call last):
  File "", line 1, in 
OSError


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


Re: assertraises behaviour

2012-07-16 Thread andrea crotti
2012/7/16 Christian Heimes :
>
> The OSError isn't catched as the code never reaches the line with "raise
> OSError". In other words "raise OSError" is never executed as the
> exception raised by "assert False" stops the context manager.
>
> You should avoid testing more than one line of code in a with
> self.assertRaises() block.
>
> Christian
>
> --
> http://mail.python.org/mailman/listinfo/python-list

Ok now it's more clear, and normally I only test one thing in the block.
But I find this quite counter-intuitive, because in the block I want
to be able to run something that raises the exception I catch (and
which I'm aware of), but if another exception is raised it *should*
show it and fail in my opinion..
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Discussion on some Code Issues

2012-07-16 Thread subhabangalore
On Sunday, July 8, 2012 10:47:00 PM UTC+5:30, Chris Angelico wrote:
> On Mon, Jul 9, 2012 at 3:05 AM,   wrote:
> > On Sunday, July 8, 2012 1:33:25 PM UTC+5:30, Chris Angelico wrote:
> >> On Sun, Jul 8, 2012 at 3:42 PM,   
> wrote:
> >> > file_open=open("/python32/doc1.txt","r")
> >> Also, as has already been mentioned: keeping your data files in the
> >> Python binaries directory isn't usually a good idea. More common 
> to
> >> keep them in the same directory as your script, which would mean that
> >> you don't need a path on it at all.
> > No file path! Amazing. I do not know I like to know one small example 
> please.
> 
> open("doc1.txt","r")
> 
> Python will look for a file called doc1.txt in the directory you run
> the script from (which is often going to be the same directory as your
> .py program).
> 
> > Btw, some earlier post said, line.split() to convert line into bag of 
> words can be done with power(), but I did not find it, if any one can help. I 
> do close files do not worry. New style I'd try.
> 
> I don't know what power() function you're talking about, and can't
> find it in the previous posts; the nearest I can find is a post from
> Ranting Rick which says a lot of guff that you can ignore. (Rick is a
> professional troll. Occasionally he says something useful and
> courteous; more often it's one or the other, or neither.)
> 
> As to the closing of files: There are a few narrow issues that make it
> worth using the 'with' statement, such as exceptions; mostly, it's
> just a good habit to get into. If you ignore it, your file will
> *usually* be closed fairly soon after you stop referencing it, but
> there's no guarantee. (Someone else will doubtless correct me if I'm
> wrong, but I'm pretty sure Python guarantees to properly flush and
> close on exit, but not necessarily before.)
> 
> ChrisA

Dear Group,

The problem is more or less solved. Thank you for giving varied ways of 
thinking on the problem. Everytime I visit the group I learn so many things. 
Thank you all for taking your kind time to try to absolve the issue.

Regards,
Subhabrata Banerjee.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python and Qt4 Designer

2012-07-16 Thread Michael Torrie
On 07/15/2012 01:58 AM, Vincent Vande Vyvre wrote:
> Rusi is not the op, and his question is about these lines
> 
> app = None
> if ( not app ):

Yeah that's a no-op.  The original author of that code is clearly
confused there.

> 
> not this one
> 
> app = QtGui.QApplication([])
> 
> which should be written like this
> 
> app = QtGui.QApplication(sys.argv)

Yeah.  The QApplication not only is the main engine, but it also parses
the command-line for certain flags that influence Qt's behavior, similar
to gtk's main function that also parses command-line flags (specific to
gtk's operation).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: assertraises behaviour

2012-07-16 Thread Christian Heimes
Am 16.07.2012 15:38, schrieb andrea crotti:
> This small example doesn't fail, but the OSError exception is cathed
> even if not declared..
> Is this the expected behaviour (from the doc I would say it's not).
> (Running on arch-linux 64 bits and Python 2.7.3, but it doesn the same
> with Python 3.2.3)
> 
> import unittest
> 
> class TestWithRaises(unittest.TestCase):
> def test_ass(self):
> with self.assertRaises(AssertionError):
> assert False, "should happen"
> raise OSError("should give error")

The OSError isn't catched as the code never reaches the line with "raise
OSError". In other words "raise OSError" is never executed as the
exception raised by "assert False" stops the context manager.

You should avoid testing more than one line of code in a with
self.assertRaises() block.

Christian

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


assertraises behaviour

2012-07-16 Thread andrea crotti
I found that the behaviour of assertRaises used as a context manager a
bit surprising.

This small example doesn't fail, but the OSError exception is cathed
even if not declared..
Is this the expected behaviour (from the doc I would say it's not).
(Running on arch-linux 64 bits and Python 2.7.3, but it doesn the same
with Python 3.2.3)

import unittest

class TestWithRaises(unittest.TestCase):
def test_ass(self):
with self.assertRaises(AssertionError):
assert False, "should happen"
raise OSError("should give error")


if __name__ == '__main__':
unittest.main()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Implicit conversion to boolean in if and while statements

2012-07-16 Thread Serhiy Storchaka

On 15.07.12 19:50, Rick Johnson wrote:

We must NEVER present "if" in such confusing manner as ExampleA.


## EXAMPLE C ##
py> if bool(money) == True:
... do_something()

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


Re: unittest: Improve discoverability of discover (Was: Initial nose experience)

2012-07-16 Thread Philipp Hagemeister
On 07/16/2012 02:37 PM, Philipp Hagemeister wrote:
> Can we improve the discoverability of the discover
> option, for example by making it the default action, or including a
> message "use discover to find test files automatically" if there are no
> arguments?
Oops, already implemented as of Python 3.2. Sorry, should've checked before.

- Philipp



signature.asc
Description: OpenPGP digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Initial nose experience

2012-07-16 Thread Ben Finney
Roy Smith  writes:

> In article ,
>  pyt...@bdurham.com wrote:
>
> > After years of using unittest, what would you say are the pros and
> > cons of nose?
>
> BTW, although I'm currently using nose just as a unittest aggregator

Be aware that Python 2.7 and higher has unit test discovery in the
standard library:

$ python -m unittest discover

will look through all packages within the current directory and collect
unit tests it finds, then run them and report
http://docs.python.org/library/unittest.html#test-discovery>.

You can get the same in earlier versions of Python with ‘unittest2’
http://pypi.python.org/pypi/unittest2>.

-- 
 \   “I prayed for twenty years but received no answer until I |
  `\  prayed with my legs.” —Frederick Douglass, escaped slave |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


unittest: Improve discoverability of discover (Was: Initial nose experience)

2012-07-16 Thread Philipp Hagemeister
On 07/16/2012 01:47 PM, Peter Otten wrote:
> http://docs.python.org/library/unittest#test-discovery

That's precisely it. Can we improve the discoverability of the discover
option, for example by making it the default action, or including a
message "use discover to find test files automatically" if there are no
arguments?

- Philipp



signature.asc
Description: OpenPGP digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Initial nose experience

2012-07-16 Thread Peter Otten
Philipp Hagemeister wrote:

> Currently, $ python -m unittest   does nothing useful (afaik). Would it
> break anything to look in . , ./test, ./tests for any files matching
> test_* , and execute those?

http://docs.python.org/library/unittest#test-discovery


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


Re: code review

2012-07-16 Thread Ben Finney
Duncan Booth  writes:

> Technically of course Python doesn't have assignment, it just binds
> names.

Names, or other references.

I'd argue that Python has assignment, and assignment in Python is
identical with binding references to objects.

But then, the Python documentation refers to “variables” as though they
exist in Python, which I'd argue they don't. It's all very confusing :-)

-- 
 \ “Religious faith is the one species of human ignorance that |
  `\ will not admit of even the *possibility* of correction.” —Sam |
_o__) Harris, _The End of Faith_, 2004 |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Initial nose experience

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

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

BTW, although I'm currently using nose just as a unittest aggregator, I 
can see some nice advantages to native nose functionality.  The most 
obvious is that tests can be plain-old static functions at the top level 
of a module.

In unittest, you have to subclass TestCase, then write methods for that 
(showing its JUnit/SUnit roots).  In 99% of the tests I write, I don't 
do anything special in my TestCase subclasses, so that's all just 
boilerplate busywork.  I like the idea that I can skip that all now.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Initial nose experience

2012-07-16 Thread Philipp Hagemeister
On 07/15/2012 08:58 PM, Roy Smith wrote:
>> 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.

Currently, $ python -m unittest   does nothing useful (afaik). Would it
break anything to look in . , ./test, ./tests for any files matching
test_* , and execute those?

- Philipp



signature.asc
Description: OpenPGP digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: code review

2012-07-16 Thread Duncan Booth
Steven D'Aprano  wrote:

> On Fri, 13 Jul 2012 12:30:47 +, Albert van der Horst wrote:
>> The worst of is, of course, = for assignment instead of := . This is
>> a convention that Python follows, to my dismay.
> 
> *shrug*
> 
> The worst is to use = for both equality and assignment, like some
> BASICs. At least Python does not allow assignment as an expression, so
> you can't make the typical C error of:
> 
> if x = y: do_something()  # oops meant x == y
> 
Technically of course Python doesn't have assignment, it just binds names.

Albert raised the subject of Algol 68 which if I remember correctly used := 
for assignment and = to bind names (although unlike Python you couldn't 
then re-bind the name to another object in the same scope).


-- 
Duncan Booth http://kupuguy.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter.event.widget: handler gets name instead of widget.

2012-07-16 Thread Frederic Rentsch
On Sat, 2012-07-14 at 20:10 -0700, rantingrickjohn...@gmail.com wrote:
> On Thursday, July 12, 2012 1:53:54 PM UTC-5, Frederic Rentsch wrote:
> 
> > The "hit list" is a table of investment titles (stock, funds, bonds)
> > that displays upon entry of a search pattern into a respective template.
> > The table displays the matching records: name, symbol, ISIN, CUSIP, Sec.
> > Any line can be click-selected. So they are to look like buttons.
> 
> Hmm. If they "appear" like a button widget anyway, then why not just use a 
> button widget?
> 

Why indeed? Why does one do simple things in a complicated way? Stations
on the sinuous path the explorer takes surveying unknown territory, I
guess. Your example below is just what I need. Thanks! 

> > Representing the mentioned names and id codes in Label widgets was the
> > simplest way I could come up with to align them in columns, admittedly
> > without the benefit of much experience. But it does look good. the
> > layout is fine.
> 
> But is it really the "simplest"? :)
> 
> ## START CODE ##
> import Tkinter as tk
> from Tkconstants import *
> 
> colWidths = (5,10,30,5)
> N_COLS = len(colWidths)
> N_ROWS = 6
> 
> root = tk.Tk()
> for r in range(N_ROWS):
> # Create some imaginary text to display in each column.
> # Also try using string methods "center" and "rjust" to
> # see alternative justification of text.
> lst = [str(r).ljust(colWidths[r]) for r in range(N_COLS)]
> b=tk.Button(root, text=''.join(lst))
> b.pack(padx=5, pady=5)
> root.mainloop()
> ## END CODE ##
> 
> You could easily expand that into something reusable.
> 
> Now. If you need to place fancy borders around the texts, or use multiple 
> fonts, or use images, or blah blah blah... then you may want to use the 
> "canvas items" provided by the Tkinter.Canvas widget INSTEAD of buttons. 
> 
> With the canvas, you can create a simple rectangle (canvas.create_rectangle) 
> that represents a button's outside dimension and give it a "button styled" 
> border. Then you can bind click events to mimic the button press action. Then 
> you can place canvas_text items on top of that fake button and configure them 
> to be invisible to click events. These text items will not interfer like the 
> Tkinter.Label widgets are currently doing. 
> 
> However, i would suggest the Tkinter.Button solution is the easiest by far.
> 
> > I find the Tkinter system quite challenging. Doing a layout isn't so
> > much a matter of dimensioning and placing things as a struggle to trick
> > a number of automatic dimensioning and placing mechanisms into
> > obliging--mechanisms that are rather numerous and hard to remember.
> 
> I don't think i agree with that assessment. 
> 

Sticky, justify, side, anchor, width, height, pad, ipad . . . a plethora
of similar formatting concepts with applicability, precedence and effect
rules that are certainly easy to work with once one knows them inside
out. Until such time it's much trial-and-error, and reading of course,
which also frequently involves guessing what is meant and cross-checking
by experiment.
   For instance, I had to find a way to control the size of frames. The
geometry mangers deflate everything bottom to top and utterly ignore
width and height specifications unless the widget is empty. The solution
I found was "spanners", frames slimmed down to zero whose length acts as
a foot in the door of their parent, as it were. I suspect there are
better ways.

> ## START TANGENTIAL MEANDERINGS ##
> I find the geometry management of Tkinter to be quite powerful whilst being 
> simultaneously simplistic. You only have three main types of management: 
> "Grid", "Place", and "Pack". Each of which has a very specific usage. One 
> caveat to know is that you can NEVER mix "Grid" and "Pack" in the same 
> container widget! I find myself using grid and pack the most, with grid being 
> at the top of the list.
> 
> Now, i will agree that grid can be confusing at first until you understand 
> how to "rowconfigure" and "columnconfigue" the containing widget (be it a 
> frame or a toplevel). There is also the "sticky" attribute to consider. 
> ## END TANGENTIAL MEANDERINGS ##
> 

Thanks for the reminder.

> But all in all, i would say the most difficult part of the Tkinter geometry 
> management API is coming to grips as to which of the three geometry managers 
> is the best choice for the particular problem at hand -- and you will find 
> yourself using more than one manager in a single GUI app!
> 
> But i don't see you solving this problem by stacking one widget on another. I 
> believe it's time to seek out a new solution.
> 

I agree. Your idea of using pre-formatted text in buttons is definitely
the way to go.  

> EASY: Using rows of Tkinter.Button coupled with a per-formatted text string.
> ADVANCED: Creating "pseudo buttons" on a canvas and stacking text objects (or 
> whatever you like) on them.

I'll keep that in mind.

Finally I can report that I found the error I st

Re: Diagramming code

2012-07-16 Thread Joel Goldstick
On Mon, Jul 16, 2012 at 3:58 AM, Ulrich Eckhardt
 wrote:
> Am 16.07.2012 03:57, schrieb hamilton:
>
>> OK then, let me ask, how do you guys learn/understand large projects ?
>
>
> 1. Use the program. This gives you an idea what features are there and a bit
> how it could be structured.
> 2. Build the program, to see what is done to get the program running. This
> should give you an idea what pieces there are and where they are [from].
> 3. Read design documentation (which is too often outdated) which should give
> you an idea what the intention of the project's structure is.
> 4. Read the code documentation (which is hopefully more up to date). This
> should give you an idea about responsibilities within the code.
> 5. Read the code itself. This can also be done while single-stepping through
> it with a debugger, just to see it run.
>
> Of course there are also secondary resources like developers' and users'
> mailinglists, websites, bugtrackers that provide information and help.
>
> Sometimes, drawing a few diagrams from steps 3 and 4 to document
> relationships between things is helpful. IMHO having a text describing the
> relationships in prose is superior to that though. In particular a diagram
> can't describe the rationale for something, you need prose for that.
>
> HTH & YMMV
>
> Uli
> --
> http://mail.python.org/mailman/listinfo/python-list

Do you know about pydoc?  Its a great way to get a handle on your
modules.  It doesn't make diagrams, but a synopsis of what is in the
module.  It makes use of docstrings, for the module and each class and
function in the module.

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


Re: Diagramming code

2012-07-16 Thread Ulrich Eckhardt

Am 16.07.2012 03:57, schrieb hamilton:

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


1. Use the program. This gives you an idea what features are there and a 
bit how it could be structured.
2. Build the program, to see what is done to get the program running. 
This should give you an idea what pieces there are and where they are 
[from].
3. Read design documentation (which is too often outdated) which should 
give you an idea what the intention of the project's structure is.
4. Read the code documentation (which is hopefully more up to date). 
This should give you an idea about responsibilities within the code.
5. Read the code itself. This can also be done while single-stepping 
through it with a debugger, just to see it run.


Of course there are also secondary resources like developers' and users' 
mailinglists, websites, bugtrackers that provide information and help.


Sometimes, drawing a few diagrams from steps 3 and 4 to document 
relationships between things is helpful. IMHO having a text describing 
the relationships in prose is superior to that though. In particular a 
diagram can't describe the rationale for something, you need prose for that.


HTH & YMMV

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


Re: Implicit conversion to boolean in if and while statements

2012-07-16 Thread Steven D'Aprano
On Sun, 15 Jul 2012 19:41:34 -0700, Ranting Rick wrote:

> 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 ([], {}, "")?


Mostly for explicitness. I want to be able to say that there is 
*explicitly* no seq, not merely that it happens to be a list which right 
now is empty but later might not be. Using None for missing values is 
idiomatic Python.

You should approve, if only for the sake of consistency: None is meant to 
be used as "no such value", and that's exactly how I am using it, even at 
the cost of my convenience when writing the code.


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


Re: Implicit conversion to boolean in if and while statements

2012-07-16 Thread Steven D'Aprano
On Sun, 15 Jul 2012 22:03:52 -0700, 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?

The problem with "String" + 1.75 is not lack of explicitness, but 
ambiguity. The + is operator is plenty explicit, but it is ambiguous when 
the operands have different types. Should it...?

- truncate "String" at the first non-digit (hence "") and then coerce
  it to 0.0, and hence return the float 1.75?

- coerce "String" to a float NaN on the basis that "String" is 
  not a number, and hence return NaN?

- coerce 1.75 to a string, and hence return "String1.75"?


The first behaviour is rather dubious, but a good case could be made for 
the second or third. Python takes a fourth approach, and refuses to allow 
such mixed type operations.

If + always meant "numeric addition", and & was used for string 
concatenation, then we could have unambiguous expressions using mixed 
types:

1 + 1.75  # int + float always coerces to float
1 + "2"   # int + str always coerces to int
1 & "2"   # int & str always coerces to str

but since & is used for integer bitwise-and, and + is used for both 
concatenation and addition, we can't, and so Python raises an exception.

For arithmetic, there is an unambiguous hierarchy of types, the numeric 
tower, which tells us which types coerce to what, e.g.:

int -> float -> complex

But there is no such hierarchy when it comes to (say) mixed strings and 
lists, etc., and hence Python raises an exception rather than guessing 
which type you wanted as the result.

This is completely irrelevant when it comes to bools -- we don't have to 
coerce a value into another type, we just need to know if it is something 
or nothing. The object itself is best able to make that decision, hence 
delegating it to a protocol and method:

- If the object is a container, and it has a length of 0, it is empty 
  and hence nothing (falsey); if it has a non-zero length, it is non-empty
  and hence something (truthy).

- Otherwise ask the container whether it is something or nothing by
  calling __nonzero__ (the original name) or __bool__.


Python makes a rather big blunder, at least from the perspective of 
consistency. Bools are ints:

py> issubclass(bool, int)
True
py> isinstance(True, int)
True
py> isinstance(False, int)
True

but there are things that can be converted into bools that can't be 
converted into ints, even though bools *are* ints! Contradiction.

py> x = [None, 42, '']
py> bool(x)
True
py> int(x)
Traceback (most recent call last):
  File "", line 1, in 
TypeError: int() argument must be a string or a number, not 'list'


Since x can be converted into True, and True == 1, you should be able to 
convert x into 1. But that's crazy, since x = [None, 42, ''].

*shrug* I don't call this a gotcha, but it is one of the more ugly 
consequences of Python's bool implementation.


> Can you
> reduce this to the absurd? Or will you just choose to ignore this valid
> point?

Mu. (Neither true nor false.)



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


Re: Implicit conversion to boolean in if and while statements

2012-07-16 Thread alex23
On Jul 16, 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?

What _other_ than booleans can you expect a condition to reduce down
to? Seriously. What might you possibly expect 'obj' in 'if obj' to be?
Tuesday? The colour mauve? That sinking feeling that you're entering
into a debate that's far above your ability to understand it?

Now: as an expression "String"+1.75 can be _anywhere_, so _what_ you
want will very much be contextual. Do you want "String1.75"? Do you
want float("String") + 1.75? Do you want it to error? So yes, here you
very much need to be explicit.

> Can you reduce this to the absurd?

You've already taken care of that.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Implicit conversion to boolean in if and while statements

2012-07-16 Thread alex23
On Jul 16, 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?

If @decorator is in essence doing "function = decorator(function)"
behind the scenes, why hide that?
If classes are just syntactic sugar for dicts of functions, why hide
that?

> It's
> obvious that "if bool(obj)" will return a boolean; whereas "if obj" is
> ambiguous.

It's only ambiguous if you're the sort of idiot who believes every
language should conform to their a priori expectations. The behaviour
is _documented and standard_, so it's in no way ambiguous unless
someone has actively failed to do _their_ part and _educate
themselves_:

http://docs.python.org/library/stdtypes.html#truth-value-testing

> If the multitudes of misunderstandings from "if obj" on this list have
> not convinced you yet

By that argument, _every_ Python feature that is misunderstood should
be modified to meet the expectations of those who have refused to
understand the language. In which case, why even bother having
different languages with different ways of doing...oh wait, I'm
talking to the monoculture king. Forget that line of reasoning.

Also: citation or STFU. Provide links to 3 threads from the last month
that have revolved around misunderstanding of truth values.

> > > 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!

Yes. That was Steven's point, which you missed in all of your usual
mouth frothing.
-- 
http://mail.python.org/mailman/listinfo/python-list