Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #46708 > unrolled thread

PyWart: The problem with "print"

Started byRick Johnson <rantingrickjohnson@gmail.com>
First post2013-06-02 10:04 -0700
Last post2013-06-03 15:11 -0400
Articles 20 on this page of 109 — 26 participants

Back to article view | Back to comp.lang.python


Contents

  PyWart: The problem with "print" Rick Johnson <rantingrickjohnson@gmail.com> - 2013-06-02 10:04 -0700
    Re: PyWart: The problem with "print" Chris Angelico <rosuav@gmail.com> - 2013-06-03 03:20 +1000
      Re: PyWart: The problem with "print" Dan Sommers <dan@tombstonezero.net> - 2013-06-02 17:49 +0000
        Re: PyWart: The problem with "print" Rick Johnson <rantingrickjohnson@gmail.com> - 2013-06-02 11:18 -0700
          Re: PyWart: The problem with "print" Ned Batchelder <ned@nedbatchelder.com> - 2013-06-02 16:45 -0400
          Re: PyWart: The problem with "print" Michael Torrie <torriem@gmail.com> - 2013-06-02 23:49 -0600
          Re: PyWart: The problem with "print" Chris Angelico <rosuav@gmail.com> - 2013-06-03 17:17 +1000
            Re: PyWart: The problem with "print" Alister <alister.ware@ntlworld.com> - 2013-06-03 08:01 +0000
      Re: PyWart: The problem with "print" Rick Johnson <rantingrickjohnson@gmail.com> - 2013-06-02 11:09 -0700
        Re: PyWart: The problem with "print" Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-06-02 19:03 +0000
        Re: PyWart: The problem with "print" Chris Angelico <rosuav@gmail.com> - 2013-06-03 06:21 +1000
        Re: PyWart: The problem with "print" jmfauth <wxjmfauth@gmail.com> - 2013-06-04 05:23 -0700
          Re: PyWart: The problem with "print" rusi <rustompmody@gmail.com> - 2013-06-04 06:29 -0700
            Re: PyWart: The problem with "print" Mark Lawrence <breamoreboy@yahoo.co.uk> - 2013-06-04 14:35 +0100
          Re: PyWart: The problem with "print" Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-06-05 05:03 +0000
    Re: PyWart: The problem with "print" Andrew Berg <robotsondrugs@gmail.com> - 2013-06-02 12:30 -0500
    Re: PyWart: The problem with "print" Chris Angelico <rosuav@gmail.com> - 2013-06-03 03:34 +1000
    Re: PyWart: The problem with "print" Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-06-02 18:58 +0000
      Re: PyWart: The problem with "print" Chris Angelico <rosuav@gmail.com> - 2013-06-03 06:28 +1000
      Re: PyWart: The problem with "print" Rick Johnson <rantingrickjohnson@gmail.com> - 2013-06-03 18:37 -0700
        Re: PyWart: The problem with "print" Vito De Tullio <vito.detullio@gmail.com> - 2013-06-04 05:16 +0200
          Re: PyWart: The problem with "print" Rick Johnson <rantingrickjohnson@gmail.com> - 2013-06-03 20:53 -0700
          Re: PyWart: The problem with "print" Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-06-04 04:30 +0000
        Bools and explicitness [was Re: PyWart: The problem with "print"] Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-06-04 05:39 +0000
          Re: Bools and explicitness [was Re: PyWart: The problem with "print"] Rick Johnson <rantingrickjohnson@gmail.com> - 2013-06-04 08:44 -0700
            Re: Bools and explicitness [was Re: PyWart: The problem with "print"] Chris Angelico <rosuav@gmail.com> - 2013-06-05 02:00 +1000
              Re: Bools and explicitness [was Re: PyWart: The problem with "print"] Rick Johnson <rantingrickjohnson@gmail.com> - 2013-06-04 09:19 -0700
                Re: Bools and explicitness [was Re: PyWart: The problem with "print"] Chris Angelico <rosuav@gmail.com> - 2013-06-05 02:27 +1000
                  Re: Bools and explicitness [was Re: PyWart: The problem with "print"] Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-06-05 05:28 +0000
                    Re: Bools and explicitness [was Re: PyWart: The problem with "print"] alex23 <wuwei23@gmail.com> - 2013-06-04 22:31 -0700
                Re: Bools and explicitness [was Re: PyWart: The problem with "print"] Ned Batchelder <ned@nedbatchelder.com> - 2013-06-04 13:25 -0400
            Re: Bools and explicitness [was Re: PyWart: The problem with "print"] Rick Johnson <rantingrickjohnson@gmail.com> - 2013-06-04 09:09 -0700
              Re: Bools and explicitness [was Re: PyWart: The problem with "print"] alex23 <wuwei23@gmail.com> - 2013-06-04 18:31 -0700
            Re: Bools and explicitness [was Re: PyWart: The problem with "print"] Fábio Santos <fabiosantosart@gmail.com> - 2013-06-04 17:10 +0100
            Re: Bools and explicitness [was Re: PyWart: The problem with "print"] Jason Swails <jason.swails@gmail.com> - 2013-06-04 13:32 -0400
            Re: Bools and explicitness [was Re: PyWart: The problem with "print"] Ian Kelly <ian.g.kelly@gmail.com> - 2013-06-04 11:42 -0600
              Re: Bools and explicitness [was Re: PyWart: The problem with "print"] Rick Johnson <rantingrickjohnson@gmail.com> - 2013-06-04 16:21 -0700
                Re: Bools and explicitness [was Re: PyWart: The problem with "print"] Mark Lawrence <breamoreboy@yahoo.co.uk> - 2013-06-05 00:37 +0100
                Re: Bools and explicitness [was Re: PyWart: The problem with "print"] Michael Torrie <torriem@gmail.com> - 2013-06-04 23:28 -0600
            Re: Bools and explicitness [was Re: PyWart: The problem with "print"] "Russ P." <Russ.Paielli@gmail.com> - 2013-06-04 23:11 -0700
              Re: Bools and explicitness [was Re: PyWart: The problem with "print"] Chris Angelico <rosuav@gmail.com> - 2013-06-05 17:15 +1000
                Re: Bools and explicitness [was Re: PyWart: The problem with "print"] "Russ P." <Russ.Paielli@gmail.com> - 2013-06-05 00:47 -0700
                Re: Bools and explicitness [was Re: PyWart: The problem with "print"] Rick Johnson <rantingrickjohnson@gmail.com> - 2013-06-06 09:49 -0700
                  Re: Bools and explicitness [was Re: PyWart: The problem with "print"] Chris Angelico <rosuav@gmail.com> - 2013-06-07 02:59 +1000
                  Re: Bools and explicitness [was Re: PyWart: The problem with "print"] Dan Stromberg <drsalists@gmail.com> - 2013-06-06 18:26 -0700
              Re: Bools and explicitness [was Re: PyWart: The problem with "print"] Mark Lawrence <breamoreboy@yahoo.co.uk> - 2013-06-05 09:59 +0100
                Re: Bools and explicitness [was Re: PyWart: The problem with "print"] "Russ P." <Russ.Paielli@gmail.com> - 2013-06-05 09:15 -0700
                  Re: Bools and explicitness [was Re: PyWart: The problem with "print"] Chris Angelico <rosuav@gmail.com> - 2013-06-06 02:59 +1000
                    Re: Bools and explicitness [was Re: PyWart: The problem with "print"] "Russ P." <Russ.Paielli@gmail.com> - 2013-06-05 14:59 -0700
                      Re: Bools and explicitness [was Re: PyWart: The problem with "print"] Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-06-06 01:56 +0000
                        Re: Bools and explicitness [was Re: PyWart: The problem with "print"] Chris Angelico <rosuav@gmail.com> - 2013-06-06 12:29 +1000
                          Re: Bools and explicitness [was Re: PyWart: The problem with "print"] "Russ P." <Russ.Paielli@gmail.com> - 2013-06-05 21:25 -0700
                            Re: Bools and explicitness [was Re: PyWart: The problem with "print"] Ian Kelly <ian.g.kelly@gmail.com> - 2013-06-06 00:06 -0600
                          Re: Bools and explicitness [was Re: PyWart: The problem with "print"] Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-06-06 09:29 +0000
                            Re: Bools and explicitness [was Re: PyWart: The problem with "print"] Chris Angelico <rosuav@gmail.com> - 2013-06-06 19:45 +1000
                            Re: Bools and explicitness [was Re: PyWart: The problem with "print"] Serhiy Storchaka <storchaka@gmail.com> - 2013-06-06 14:12 +0300
                            Re: Bools and explicitness [was Re: PyWart: The problem with "print"] Robert Kern <robert.kern@gmail.com> - 2013-06-06 16:35 +0100
                            Re: Bools and explicitness [was Re: PyWart: The problem with "print"] Chris Angelico <rosuav@gmail.com> - 2013-06-07 01:41 +1000
                            Re: Bools and explicitness [was Re: PyWart: The problem with "print"] Robert Kern <robert.kern@gmail.com> - 2013-06-06 17:08 +0100
                              Re: Bools and explicitness [was Re: PyWart: The problem with "print"] rusi <rustompmody@gmail.com> - 2013-06-06 10:27 -0700
                                Re: Bools and explicitness [was Re: PyWart: The problem with "print"] Devin Jeanpierre <jeanpierreda@gmail.com> - 2013-06-06 14:44 -0400
                            Re: Bools and explicitness [was Re: PyWart: The problem with "print"] Mark Janssen <dreamingforward@gmail.com> - 2013-06-06 10:59 -0700
                              Re: Bools and explicitness [was Re: PyWart: The problem with "print"] alex23 <wuwei23@gmail.com> - 2013-06-06 17:53 -0700
                                Re: Bools and explicitness [was Re: PyWart: The problem with "print"] Mark Janssen <dreamingforward@gmail.com> - 2013-06-06 18:44 -0700
                                  Re: Bools and explicitness [was Re: PyWart: The problem with "print"] alex23 <wuwei23@gmail.com> - 2013-06-06 19:03 -0700
                                    Re: Bools and explicitness [was Re: PyWart: The problem with "print"] Mark Janssen <dreamingforward@gmail.com> - 2013-06-06 22:01 -0700
                                  Re: Bools and explicitness [was Re: PyWart: The problem with "print"] Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-06-07 02:29 +0000
                                    Re: Bools and explicitness [was Re: PyWart: The problem with "print"] Mark Janssen <dreamingforward@gmail.com> - 2013-06-06 20:14 -0700
                                      Re: Bools and explicitness [was Re: PyWart: The problem with "print"] rusi <rustompmody@gmail.com> - 2013-06-06 20:24 -0700
                                        Re: Bools and explicitness [was Re: PyWart: The problem with "print"] Mark Janssen <dreamingforward@gmail.com> - 2013-06-06 20:30 -0700
                                        Re: Bools and explicitness [was Re: PyWart: The problem with "print"] rusi <rustompmody@gmail.com> - 2013-06-06 20:43 -0700
                            Re: Bools and explicitness [was Re: PyWart: The problem with "print"] "Russ P." <Russ.Paielli@gmail.com> - 2013-06-06 11:08 -0700
                    Re: Bools and explicitness [was Re: PyWart: The problem with "print"] Rick Johnson <rantingrickjohnson@gmail.com> - 2013-06-06 08:49 -0700
                      Re: Bools and explicitness [was Re: PyWart: The problem with "print"] Chris Angelico <rosuav@gmail.com> - 2013-06-07 02:00 +1000
                        Re: Bools and explicitness [was Re: PyWart: The problem with "print"] Grant Edwards <invalid@invalid.invalid> - 2013-06-06 17:32 +0000
                  Re: Bools and explicitness [was Re: PyWart: The problem with "print"] Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-06-06 01:37 +0000
                    Re: Bools and explicitness [was Re: PyWart: The problem with "print"] Chris Angelico <rosuav@gmail.com> - 2013-06-06 11:45 +1000
                      Re: Bools and explicitness [was Re: PyWart: The problem with "print"] rusi <rustompmody@gmail.com> - 2013-06-06 07:09 -0700
                        Re: Bools and explicitness [was Re: PyWart: The problem with "print"] Chris Angelico <rosuav@gmail.com> - 2013-06-07 01:26 +1000
                          Re: Bools and explicitness [was Re: PyWart: The problem with "print"] rusi <rustompmody@gmail.com> - 2013-06-06 08:36 -0700
                            Re: Bools and explicitness [was Re: PyWart: The problem with "print"] Chris Angelico <rosuav@gmail.com> - 2013-06-07 01:46 +1000
                    Re: Bools and explicitness [was Re: PyWart: The problem with "print"] Rick Johnson <rantingrickjohnson@gmail.com> - 2013-06-06 11:03 -0700
                      Re: Bools and explicitness [was Re: PyWart: The problem with "print"] Rick Johnson <rantingrickjohnson@gmail.com> - 2013-06-06 11:11 -0700
              Re: Bools and explicitness [was Re: PyWart: The problem with "print"] Terry Jan Reedy <tjreedy@udel.edu> - 2013-06-05 12:10 -0400
              Re: Bools and explicitness [was Re: PyWart: The problem with "print"] Michael Torrie <torriem@gmail.com> - 2013-06-05 17:18 -0600
                Re: Bools and explicitness [was Re: PyWart: The problem with "print"] "Russ P." <Russ.Paielli@gmail.com> - 2013-06-05 16:52 -0700
                  Re: Bools and explicitness [was Re: PyWart: The problem with "print"] Michael Torrie <torriem@gmail.com> - 2013-06-05 19:20 -0600
                Re: Bools and explicitness [was Re: PyWart: The problem with "print"] Rick Johnson <rantingrickjohnson@gmail.com> - 2013-06-06 09:24 -0700
                  Re: Bools and explicitness [was Re: PyWart: The problem with "print"] Devin Jeanpierre <jeanpierreda@gmail.com> - 2013-06-06 12:39 -0400
                    Re: Bools and explicitness [was Re: PyWart: The problem with "print"] alex23 <wuwei23@gmail.com> - 2013-06-06 17:55 -0700
        Re: PyWart: The problem with "print" Chris Angelico <rosuav@gmail.com> - 2013-06-04 17:30 +1000
    Re: PyWart: The problem with "print" Jason Swails <jason.swails@gmail.com> - 2013-06-02 20:16 -0400
      Re: PyWart: The problem with "print" Dan Sommers <dan@tombstonezero.net> - 2013-06-03 03:10 +0000
        Re: PyWart: The problem with "print" Jason Swails <jason.swails@gmail.com> - 2013-06-02 23:23 -0400
          Re: PyWart: The problem with "print" Dan Sommers <dan@tombstonezero.net> - 2013-06-03 04:20 +0000
            Re: PyWart: The problem with "print" Robert Kern <robert.kern@gmail.com> - 2013-06-03 11:52 +0100
        Re: PyWart: The problem with "print" Tim Delaney <timothy.c.delaney@gmail.com> - 2013-06-03 13:37 +1000
          Python Heisenbugs?  (was: Re: PyWart: The problem with "print") Dan Sommers <dan@tombstonezero.net> - 2013-06-03 04:34 +0000
            Re: Python Heisenbugs? (was: Re: PyWart: The problem with "print") Chris Angelico <rosuav@gmail.com> - 2013-06-03 15:05 +1000
            Re: Python Heisenbugs? (was: Re: PyWart: The problem with "print") Devin Jeanpierre <jeanpierreda@gmail.com> - 2013-06-03 03:06 -0400
        Re: PyWart: The problem with "print" Mark Lawrence <breamoreboy@yahoo.co.uk> - 2013-06-03 09:49 +0100
        Re: PyWart: The problem with "print" Dave Angel <davea@davea.name> - 2013-06-03 08:56 -0400
    Re: PyWart: The problem with "print" Chris Angelico <rosuav@gmail.com> - 2013-06-03 12:02 +1000
    Re: PyWart: The problem with "print" Ian Kelly <ian.g.kelly@gmail.com> - 2013-06-03 11:12 -0600
    Re: PyWart: The problem with "print" Jason Swails <jason.swails@gmail.com> - 2013-06-03 15:09 -0400
      Re: PyWart: The problem with "print" Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-06-03 20:31 +0000
        Re: PyWart: The problem with "print" Chris Angelico <rosuav@gmail.com> - 2013-06-04 06:44 +1000
    Re: PyWart: The problem with "print" Jason Swails <jason.swails@gmail.com> - 2013-06-03 15:10 -0400
    Re: PyWart: The problem with "print" Jason Swails <jason.swails@gmail.com> - 2013-06-03 15:11 -0400

Page 2 of 6 — ← Prev page 1 [2] 3 4 5 6  Next page →


#46830

FromVito De Tullio <vito.detullio@gmail.com>
Date2013-06-04 05:16 +0200
Message-ID<mailman.2620.1370315799.3114.python-list@python.org>
In reply to#46827
Rick Johnson wrote:

> Take your
> standard yes/no/cancel dialog, i would expect it to return
> True|False|None respectively,

you clearly mean True / False / FileNotFound.

( http://thedailywtf.com/Articles/What_Is_Truth_0x3f_.aspx )

-- 
ZeD

[toc] | [prev] | [next] | [standalone]


#46832

FromRick Johnson <rantingrickjohnson@gmail.com>
Date2013-06-03 20:53 -0700
Message-ID<5e24150b-475d-48d5-a905-03f400381919@googlegroups.com>
In reply to#46830
On Monday, June 3, 2013 10:16:13 PM UTC-5, Vito De Tullio wrote:
> Rick Johnson wrote:
> > Take your
> > standard yes/no/cancel dialog, i would expect it to return
> > True|False|None respectively,
> you clearly mean True / False / FileNotFound.

No, i clearly meant what i said :-). FileDialogs only return
one of two values; either a valid path or a value
representing "failure". I suppose FileNotFound is a custom
exception? That will work however i wonder if exception
handling is overkill for this?

  try:
      path = filedialog.open("path")
  except FileNotFound:
      return
  do_something(path)

As opposed to:

  path = filedialog.open("path")
  if path:
      do_something(path)

Or, if Python was really cool!

  if filedialog.open("path") as path:
      do_something(path)

However, i think True|False|None is the best return values
for a yes|no|cancel choice. Consider:

  result = yesnocancel("save changes?")
  if result:
      # Try to save changes and close.
      if self.fileSave():
          app.close()
      else:
          show_error()
  elif result is False:
      # Close without saving changes.
      app.close()
  else:
      # Canceled: Do nothing.
      return

[toc] | [prev] | [next] | [standalone]


#46833

FromSteven D'Aprano <steve+comp.lang.python@pearwood.info>
Date2013-06-04 04:30 +0000
Message-ID<51ad6d5f$0$11118$c3e8da3@news.astraweb.com>
In reply to#46830
On Tue, 04 Jun 2013 05:16:13 +0200, Vito De Tullio wrote:

> Rick Johnson wrote:
> 
>> Take your
>> standard yes/no/cancel dialog, i would expect it to return
>> True|False|None respectively,
> 
> you clearly mean True / False / FileNotFound.
> 
> ( http://thedailywtf.com/Articles/What_Is_Truth_0x3f_.aspx )


No no, he actually means 

return True
return False
raise an exception


Or perhaps 

0
1
2

Or perhaps:

'yes'
'no'
'cancel'

like all right-thinking people expect *wink*

Of course the one thing that a programmer should never, ever do, under 
pain of maybe having to learn something, is actually check the 
documentation of an unfamiliar library or function before making 
assumptions of what it will return. If you follow this advice, you too 
can enjoy the benefits of writing buggy code.



-- 
Steven

[toc] | [prev] | [next] | [standalone]


#46836 — Bools and explicitness [was Re: PyWart: The problem with "print"]

FromSteven D'Aprano <steve+comp.lang.python@pearwood.info>
Date2013-06-04 05:39 +0000
SubjectBools and explicitness [was Re: PyWart: The problem with "print"]
Message-ID<51ad7daf$0$11118$c3e8da3@news.astraweb.com>
In reply to#46827
On Mon, 03 Jun 2013 18:37:24 -0700, Rick Johnson wrote:
> On Sunday, June 2, 2013 1:58:30 PM UTC-5, Steven D'Aprano wrote:
>> On Sun, 02 Jun 2013 10:04:00 -0700, Rick Johnson wrote:

>> > A "wise programmer" may think he's solved the problem by writing a
>> > function called "debugprint" that looks like this:
>> > >     def debugprint(*args):
>> >         if DEBUG == True:
>> >             print(*args)
>>
>> No no no, that's not how you do it. It should be:
>>     if DEBUG == True == True:
>>
>> Wait, no, I got that wrong. It should be:
>>     if DEBUG == True == True == True:
>>
>> Hang on, I've nearly got it!
>>     if DEBUG == True == True == True == True:
>>
>> Or, you could program like a professional, and say:
>>     if DEBUG:
> 
> Obviously you don't appreciate the value of "explicit enough".
> 
>   if VALUE:
> 
> is not explicit enough, however

Consider a simple thought experiment. Suppose we start with a sequence of 
if statements that begin simple and get more complicated:

if a == 1: ...

if a == 1 and b > 2*c: ...

if a == 1 and b > 2*c or d%4 == 1: ...

if a == 1 and b > 2*c or d%4 == 1 and not (d**3//7)%3 == 0: ...


I don't believe that any of these tests are improved by adding an 
extraneous "== True" at the end:

if (a == 1) == True: ...

if (a == 1 and b > 2*c) == True: ...

if (a == 1 and b > 2*c or d%4 == 1) == True: ...

if (a == 1 and b > 2*c or d%4 == 1 and not (d**3//7)%3 == 0) == True: ...

At some point your condition becomes so complicated that you may wish to 
save it as a separate variable, or perhaps you need to check the flag in 
a couple of places and so calculate it only once. Moving the flag out 
into a separate variable doesn't make "== True" any more useful or 
helpful.

flag = a == 1
if flag == True: ...


But even if it did, well, you've just entered the Twilight Zone, because 
of course "flag == True" is just a flag, so it too needs to be tested 
with "== True":

flag = (a == 1) == True
if flag == True: ...

but that too is just a flag so it needs more "explicitness"... and so on 
forever. This conclusion is of course nonsense. Adding "== True" to your 
boolean tests isn't helpful, so there's no need for even one, let alone 
an infinite series of "== True".

"if flag" is as explicit as it needs to be. There's no need to 
artificially inflate the "explicitness" as if being explicit was good in 
and of itself. We don't normally write code like this:

n += int(1)

just to be explicit about 1 being an int. That would be redundant and 
silly. In Python, 1 *is* an int.


[...]
>   if lst:
> 
> I don't like that because it's too implict. What exactly about the list
> are we wanting to test?

If you are unfamiliar with Python, then you have to learn what the 
semantics of "if lst" means. Just as you would have to learn what 
"if len(lst) > 0" means.


> I prefer to be explicit at the cost of a few keystrokes:
> 
>   if len(lst) > 0:

This line of code is problematic, for various reasons:

- you're making assumptions about the object which are unnecessary;

- which breaks duck-typing;

- and risks doing too much work, or failing altogether.

You're looking up the length of the lst object, but you don't really care 
about the length. You only care about whether there is something there or 
not, whether lst is empty or not. It makes no difference whether lst 
contains one item or one hundred million items, and yet you're asking to 
count them all. Only to throw that count away immediately!

Looking at the length of a built-in list is cheap, but why assume it is a 
built-in list? Perhaps it is a linked list where counting the items 
requires a slow O(N) traversal of the entire list. Or some kind of lazy 
sequence that has no way of counting the items remaining, but knows 
whether it is exhausted or not.

The Python way is to duck-type, and to let the lst object decide for 
itself whether it's empty or not:

if lst: ...


not to make assumptions about the specific type and performance of the 
object.


> Consider the following:
> 
>  What if the symbol `value` is expected to be a list, however, somehow
>  it accidentally got reassigned to another type. If i choose to be
>  implicit and use: "if value", the code could silently work for a type i
>  did not intend, therefore the program could go on for quite some time
>  before failing suddenly on attribute error, or whatever.

`if len(lst) > 0` also works for types you don't intend. Any type that 
defines a __len__ method which returns an integer will do it.

Tuples, sets and dicts are just the most obvious examples of things that 
support len() but do not necessarily support all the things you might 
wish to do to a list.



> However, if i choose to be explicit and use:
> 
>   "if len(VALUE) > 0:
> 
> then the code will fail when it should: at the comparison line.

Except of course when it doesn't.


> Because
> any object that does not provide a __len__ method would cause Python to
> raise NameError.

TypeError.



> By being "explicit enough" i will inject readability and safety into my
> code base. 

Unnecessary verbosity and redundancy, unnecessary restrictions on the 
type of the object, and unjustifiable assumptions about the cost of 
calling len().


-- 
Steven

[toc] | [prev] | [next] | [standalone]


#46923 — Re: Bools and explicitness [was Re: PyWart: The problem with "print"]

FromRick Johnson <rantingrickjohnson@gmail.com>
Date2013-06-04 08:44 -0700
SubjectRe: Bools and explicitness [was Re: PyWart: The problem with "print"]
Message-ID<c694719e-03d7-485c-a88b-0a7770d4d133@googlegroups.com>
In reply to#46836
On Tuesday, June 4, 2013 12:39:59 AM UTC-5, Steven D'Aprano wrote:
> On Mon, 03 Jun 2013 18:37:24 -0700, Rick Johnson wrote:

> Consider a simple thought experiment. Suppose we start with a sequence of 
> if statements that begin simple and get more complicated:
> if a == 1: ...
> if a == 1 and b > 2*c: ...
> if a == 1 and b > 2*c or d%4 == 1: ...
> if a == 1 and b > 2*c or d%4 == 1 and not (d**3//7)%3 == 0: ...
> I don't believe that any of these tests are improved by adding an 
> extraneous "== True" at the end:
> if (a == 1) == True: ...
> if (a == 1 and b > 2*c) == True: ...
> if (a == 1 and b > 2*c or d%4 == 1) == True: ...
> if (a == 1 and b > 2*c or d%4 == 1 and not (d**3//7)%3 == 0) == True: ...

And i agree!

You are misunderstanding my very valid point. Post-fixing a
"== True" when truth testing a *real* Boolean (psst: that's
a True or False object) is superfluous, I'm referring to
truth testing non-Boolean values. So with that in mind, the
following is acceptably "explicit enough" for me:

    a = True
    if a:
        do_something()
    
However, since Python allows implicit conversion to Boolean
for ALL types, unless we know for sure, beyond any
reasonable doubt, that the variable we are truth testing is
pointing to a True or False object, we are taking too many
chances and will eventually create subtle bugs.
    
    a = " "
    if a:
        do_something()

When if write code that "truth tests", i expect that the
value i'm testing is a True or False object, not an empty
list that *magically* converts to False when i place an "if"
in front of it, or a list with more members that magically
converts to True when i place an "if" in front of it.

This implicit conversion seems like a good idea at first,
and i was caught up in the hype myself for some time: "Hey,
i can save a few keystrokes, AWESOME!". However, i can tell
you with certainty that this implicit conversion is folly.
It is my firm belief that truth testing a value that is not
a Boolean should raise an exception. If you want to convert
a type to Boolean then pass it to the bool function:

    lst = [1,2,3]
    if bool(lst):
        do_something

This would be "explicit enough"


> If you are unfamiliar with Python, then you have to learn what the 
> semantics of "if lst" means. Just as you would have to learn what 
> "if len(lst) > 0" means.

Again, i understand the folly of "implicit Boolean
conversion" just fine.

> > I prefer to be explicit at the cost of a few keystrokes:
> >   if len(lst) > 0:
> This line of code is problematic, for various reasons:
> - you're making assumptions about the object which are unnecessary;
> - which breaks duck-typing;
> - and risks doing too much work, or failing altogether.
> You're looking up the length of the lst object, but you don't really care 
> about the length. 

Yes i do care about the length or i would not have asked.
I'm asking Python to tell me if the iterable has members,
amd if it does, i want to execute a block of code, if it
does not, i want to do nothing. But i'm also informing the
reader of my source code that the symbol i am truth testing
is expected to be an iterable with a __len__ method.

"if lst" does not give me the same answer (or imply the same
meaning to a reader), it merely tells me that the implict
conversion has resulted in a True value, but what if the lst
symbol is pointing to a string? Then i will falsely believe
i have a list with members when i actually have a string
with length greater than zero.

> You only care about whether there is something there or 
> not, whether lst is empty or not. It makes no difference whether lst 
> contains one item or one hundred million items, and yet you're asking to 
> count them all. Only to throw that count away immediately!

I agree. Summing the list members just to guarantee that the
iterable has members is foolish, however, python gives me no
other choice IF i want to be "explicit enough". In a
properly designed language, the base iterable object would
supply a "hasLength" or "hasMembers" method that would
return a much faster check of:

    try:
        iterable[0]
    except IndexError:
        return False
    else:
        return True

That check would guarantee the iterable contained at least
one member without counting them all.

> Looking at the length of a built-in list is cheap, but why assume it is a 
> built-in list? Perhaps it is a linked list where counting the items 
> requires a slow O(N) traversal of the entire list. Or some kind of lazy 
> sequence that has no way of counting the items remaining, but knows 
> whether it is exhausted or not.

Yes, but the problem is not "my approach", rather the lack
of proper language design (my apologizes to the "anointed
one". ;-)

> The Python way is to duck-type, and to let the lst object decide for 
> itself whether it's empty or not:
> if lst: ...
> not to make assumptions about the specific type and performance of the 
> object.

Well Steven, in the real world sometimes you have no other
choice. I don't have time to read and comprehend thousands
of lines of code just to use a simple interface. We are all
aware that:

  "Look Before You Leap"

is always a slower method than: 

  "It's Easier to Ask Forgiveness Than Permission"

When i am writing code i prefer to be "explicit enough" so
that IF my assumptions about the exact type of an object are
incorrect, the code will fail quickly enough that i can
easily find and correct the problem. In this manner i can
develop code much faster because i do not need to understand
the minutia of an API in order to wield it. On the contrary,
Implicit Conversion to Boolean is a bug producing nightmare
that requires too much attention to minutia.

> > Consider the following:
> >  What if the symbol `value` is expected to be a list, however, somehow
> >  it accidentally got reassigned to another type. If i choose to be
> >  implicit and use: "if value", the code could silently work for a type i
> >  did not intend, therefore the program could go on for quite some time
> >  before failing suddenly on attribute error, or whatever.
> `if len(lst) > 0` also works for types you don't intend. Any type that 
> defines a __len__ method which returns an integer will do it.
> Tuples, sets and dicts are just the most obvious examples of things that 
> support len() but do not necessarily support all the things you might 
> wish to do to a list.

Agreed. 

The "if len(var) > 0" will return True for ANY object that
includes a __len__ method. This test is fine if you want to
test iterables generically, however, if you want to be
specific about testing lists you could not rely on that code
because strings and all other iterables would return the
same "truthy" or "falsey" value. But how do we solve this
issue? I don't want to see this:

    if isinstance(var, list) and len(var) > 0:
       do_something()
       
But we are really ignoring the elephant in the room. Implict
conversion to Boolean is just a drop in the bucket compared
to the constant "shell game" we are subjected to when
reading source code. We so naively believe that a symbol
named "lst" is a list object or a symbol "age" is a integer,
when we could be totally wrong! This is the source of many
subtle bugs!!!

There must be some method by which we can truth test an
iterable object and verify it has members, but do so in a
manner that is valid for all types AND exposes the "expected
type" in the method name. hmm...

Adding a method like "is_valid" to every object can seem
logical, however, this can fail just as miserably as
Python's current implicit bool. And, more disastrously, an
"is_valid" method is not going to raise an error (where it
should) because it works for all types.

What we need is a method by which we can validate a symbol
and simultaneously do the vaidation in a manner that will
cast light on the type that is expected. In order for this
to work, you would need validators with unique "type names"

    if var.is_validList():
    elif var.is_validString():
    elif var.is_vaildTuple():
    elif var.is_validInteger():
    elif var.is_validFloat():
    elif var.is_validDict():
    etc...

By this manner, we can roll three common tests into one
method:

    * boolean conversion
    * member truthiness for iterables
    * type checking

But most importantly, we destroy implicitly and and be
"explicit enough", but not so explicit that our fingers
hurt.

*school-bell-rings*

PS: Damn i'm good! I believe the BDFL owes me a Thank You
email for this gold i just dropped on the Python community.
Flattery is welcome. Pucker up!

[toc] | [prev] | [next] | [standalone]


#46930 — Re: Bools and explicitness [was Re: PyWart: The problem with "print"]

FromChris Angelico <rosuav@gmail.com>
Date2013-06-05 02:00 +1000
SubjectRe: Bools and explicitness [was Re: PyWart: The problem with "print"]
Message-ID<mailman.2661.1370361647.3114.python-list@python.org>
In reply to#46923
On Wed, Jun 5, 2013 at 1:44 AM, Rick Johnson
<rantingrickjohnson@gmail.com> wrote:
> But we are really ignoring the elephant in the room. Implict
> conversion to Boolean is just a drop in the bucket compared
> to the constant "shell game" we are subjected to when
> reading source code. We so naively believe that a symbol
> named "lst" is a list object or a symbol "age" is a integer,
> when we could be totally wrong! This is the source of many
> subtle bugs!!!

You know, if you want a language with strict type declarations and
extreme run-time efficiency, there are some around. I think one of
them might even be used to make the most popular Python. Give it a
try, you might like it! There's NO WAY that you could accidentally
pass a list to a function that's expecting a float, NO WAY to
unexpectedly call a method on the wrong type of object. It would suit
you perfectly!

ChrisA

[toc] | [prev] | [next] | [standalone]


#46936 — Re: Bools and explicitness [was Re: PyWart: The problem with "print"]

FromRick Johnson <rantingrickjohnson@gmail.com>
Date2013-06-04 09:19 -0700
SubjectRe: Bools and explicitness [was Re: PyWart: The problem with "print"]
Message-ID<df42b0cb-cd56-4051-aecb-445f07cc9f44@e13g2000yqp.googlegroups.com>
In reply to#46930
On Jun 4, 11:00 am, Chris Angelico <ros...@gmail.com> wrote:
> You know, if you want a language with strict type declarations and
> extreme run-time efficiency, there are some around.

I don't like declaring types everywhere, i hate it. I prefer duck
typed languages, HOWEVER, in order for duck typing to work
consistently you must have checks and balances that the programmer can
apply when he feels necessary. My "is_valid" built in will bridge the
gap. We won't be forced to declare types, but we should ALWAYS add
"type checks" to our "truth tests" unless we want to create subtle
bugs. "is_valid" IS the answer!

[toc] | [prev] | [next] | [standalone]


#46938 — Re: Bools and explicitness [was Re: PyWart: The problem with "print"]

FromChris Angelico <rosuav@gmail.com>
Date2013-06-05 02:27 +1000
SubjectRe: Bools and explicitness [was Re: PyWart: The problem with "print"]
Message-ID<mailman.2665.1370363254.3114.python-list@python.org>
In reply to#46936
On Wed, Jun 5, 2013 at 2:19 AM, Rick Johnson
<rantingrickjohnson@gmail.com> wrote:
> On Jun 4, 11:00 am, Chris Angelico <ros...@gmail.com> wrote:
>> You know, if you want a language with strict type declarations and
>> extreme run-time efficiency, there are some around.
>
> I don't like declaring types everywhere, i hate it. I prefer duck
> typed languages, HOWEVER, in order for duck typing to work
> consistently you must have checks and balances that the programmer can
> apply when he feels necessary. My "is_valid" built in will bridge the
> gap. We won't be forced to declare types, but we should ALWAYS add
> "type checks" to our "truth tests" unless we want to create subtle
> bugs. "is_valid" IS the answer!

Option 1:

void C_function(int x)

Option 2:

def Python_function(x):
    assert isinstance(x,int)

Is there a fundamental difference? You're basically proposing Option 2
while detesting Option 1.

ChrisA

[toc] | [prev] | [next] | [standalone]


#47017 — Re: Bools and explicitness [was Re: PyWart: The problem with "print"]

FromSteven D'Aprano <steve+comp.lang.python@pearwood.info>
Date2013-06-05 05:28 +0000
SubjectRe: Bools and explicitness [was Re: PyWart: The problem with "print"]
Message-ID<51aecc90$0$11118$c3e8da3@news.astraweb.com>
In reply to#46938
On Wed, 05 Jun 2013 02:27:26 +1000, Chris Angelico wrote:

> On Wed, Jun 5, 2013 at 2:19 AM, Rick Johnson
> <rantingrickjohnson@gmail.com> wrote:
>> On Jun 4, 11:00 am, Chris Angelico <ros...@gmail.com> wrote:
>>> You know, if you want a language with strict type declarations and
>>> extreme run-time efficiency, there are some around.
>>
>> I don't like declaring types everywhere, i hate it. I prefer duck typed
>> languages, HOWEVER, in order for duck typing to work consistently you
>> must have checks and balances that the programmer can apply when he
>> feels necessary. My "is_valid" built in will bridge the gap. We won't
>> be forced to declare types, but we should ALWAYS add "type checks" to
>> our "truth tests" unless we want to create subtle bugs. "is_valid" IS
>> the answer!
> 
> Option 1:
> 
> void C_function(int x)
> 
> Option 2:
> 
> def Python_function(x):
>     assert isinstance(x,int)
> 
> Is there a fundamental difference? You're basically proposing Option 2
> while detesting Option 1.


How many years has Rick been coming here, proclaiming loudly how much he 
loves Python's duck-typing? Ten years? And yet, he still has no clue what 
it actually means.

If you're performing a type-check, IT ISN'T DUCK-TYPING.

Duck typing means you don't care whether you have an int, so long as 
whatever object you get is usable where an int is usable. 

Now, there are many places in my own code where I decide that I wish to 
prohibit duck-typing. "Here I insist on an actual int, not just any old 
number." There are, sometimes, good reasons for this. But every time I do 
this, I am *not* duck-typing, I am doing a runtime type check which is 
completely opposite in intent to duck-typing. (There's no short name for 
this -- it's not quite static typing, because it happens at runtime and 
isn't enforced by the language.) 

It's almost like Rick declares that he's a great supporter of the free 
market, and that everyone should be free to buy and trade in whatever 
property they wish, while insisting that nothing can be bought or sold 
without permission from the government first.



-- 
Steven

[toc] | [prev] | [next] | [standalone]


#47019 — Re: Bools and explicitness [was Re: PyWart: The problem with "print"]

Fromalex23 <wuwei23@gmail.com>
Date2013-06-04 22:31 -0700
SubjectRe: Bools and explicitness [was Re: PyWart: The problem with "print"]
Message-ID<3f548bb7-f614-49c1-bbcb-1ff4782cae5e@lr16g2000pbb.googlegroups.com>
In reply to#47017
On Jun 5, 3:28 pm, Steven D'Aprano <steve
+comp.lang.pyt...@pearwood.info> wrote:
> How many years has Rick been coming here, proclaiming loudly <x> [a]nd yet, he still has no clue what
> <x> actually means.

It's not just duck typing.

[toc] | [prev] | [next] | [standalone]


#46945 — Re: Bools and explicitness [was Re: PyWart: The problem with "print"]

FromNed Batchelder <ned@nedbatchelder.com>
Date2013-06-04 13:25 -0400
SubjectRe: Bools and explicitness [was Re: PyWart: The problem with "print"]
Message-ID<mailman.2668.1370366799.3114.python-list@python.org>
In reply to#46936
On 6/4/2013 12:19 PM, Rick Johnson wrote:
> On Jun 4, 11:00 am, Chris Angelico <ros...@gmail.com> wrote:
>> You know, if you want a language with strict type declarations and
>> extreme run-time efficiency, there are some around.
> I don't like declaring types everywhere, i hate it. I prefer duck
> typed languages, HOWEVER, in order for duck typing to work
> consistently you must have checks and balances that the programmer can
> apply when he feels necessary. My "is_valid" built in will bridge the
> gap. We won't be forced to declare types, but we should ALWAYS add
> "type checks" to our "truth tests" unless we want to create subtle
> bugs. "is_valid" IS the answer!
>

You are mis-using the term "duck typing." It doesn't mean just, "no type 
declarations." It also means, "the type of the value is irrelevant, all 
that matters is what it can do."  Insisting that something be a list (or 
a dict, ...) is unnecessary and counter to the duck-typing philosophy.  
What's important is that you can iterate, or index it, or whatever it is 
you want to do with the list.  The abstract base classes in the 
collections module were designed to help with determining these 
capabilities: 
http://docs.python.org/2/library/collections.html#collections-abstract-base-classes 
Of course, often, it's best just to do what you want to do rather than 
checking first.

Also, I have no idea why [] isn't a "valid" list.  Surely different 
applications will have different needs for what counts as valid once the 
type-check is passed.

--Ned.

[toc] | [prev] | [next] | [standalone]


#46934 — Re: Bools and explicitness [was Re: PyWart: The problem with "print"]

FromRick Johnson <rantingrickjohnson@gmail.com>
Date2013-06-04 09:09 -0700
SubjectRe: Bools and explicitness [was Re: PyWart: The problem with "print"]
Message-ID<57f4d421-3941-4cff-8bff-84a670226d2d@g8g2000yqa.googlegroups.com>
In reply to#46923
On Jun 4, 10:44 am, Rick Johnson <rantingrickjohn...@gmail.com> wrote:

> What we need is a method by which we can validate a symbol
> and simultaneously do the vaidation in a manner that will
> cast light on the type that is expected. In order for this
> to work, you would need validators with unique "type names"
>
>     if var.is_validList():
>     elif var.is_validString():
>     elif var.is_vaildTuple():
>     elif var.is_validInteger():
>     elif var.is_validFloat():
>     elif var.is_validDict():
>     etc...

Actually, instead of forcing all types to have many "specific"
methods, one builtin could solve the entire issue. The function would
be similar to isinstance() taking two arguments "object" and "type",
however, it will not only guarantee type but also handle the
conversion to Boolean:

   if is_valid(var, list):
       # if this block executes we know
       # the var is of <type list> and
       # var.length is greater than one.
   else:
       # if this block executes we know
       # that var is not of <type list>
       # or, var.length equals zero.

The is_valid function would replace implicit Boolean conversion for
all types in manner that is "explicit enough" whilst maintaining
finger longevity. This is how you design a language for consistency
and readability.

Again. PUCKER UP WHO-VILLE!

[toc] | [prev] | [next] | [standalone]


#46993 — Re: Bools and explicitness [was Re: PyWart: The problem with "print"]

Fromalex23 <wuwei23@gmail.com>
Date2013-06-04 18:31 -0700
SubjectRe: Bools and explicitness [was Re: PyWart: The problem with "print"]
Message-ID<3710b22e-8e12-482f-8e7d-9105b550c323@a15g2000pbu.googlegroups.com>
In reply to#46934
On Jun 5, 2:09 am, Rick Johnson <rantingrickjohn...@gmail.com> wrote:
> This is how you design a language for consistency and readability.

Great! Now you can shut up and get back to work on RickPython4000.
Come back and let us know all about it when it's done.

[toc] | [prev] | [next] | [standalone]


#46935 — Re: Bools and explicitness [was Re: PyWart: The problem with "print"]

FromFábio Santos <fabiosantosart@gmail.com>
Date2013-06-04 17:10 +0100
SubjectRe: Bools and explicitness [was Re: PyWart: The problem with "print"]
Message-ID<mailman.2663.1370362263.3114.python-list@python.org>
In reply to#46923

[Multipart message — attachments visible in raw view] — view raw

On 4 Jun 2013 17:04, "Chris Angelico" <rosuav@gmail.com> wrote:
>
> On Wed, Jun 5, 2013 at 1:44 AM, Rick Johnson
> <rantingrickjohnson@gmail.com> wrote:
> > But we are really ignoring the elephant in the room. Implict
> > conversion to Boolean is just a drop in the bucket compared
> > to the constant "shell game" we are subjected to when
> > reading source code. We so naively believe that a symbol
> > named "lst" is a list object or a symbol "age" is a integer,
> > when we could be totally wrong! This is the source of many
> > subtle bugs!!!
>
> You know, if you want a language with strict type declarations and
> extreme run-time efficiency, there are some around. I think one of
> them might even be used to make the most popular Python. Give it a
> try, you might like it! There's NO WAY that you could accidentally
> pass a list to a function that's expecting a float, NO WAY to
> unexpectedly call a method on the wrong type of object. It would suit
> you perfectly!
>

I agree. I have never had this kind of issues in a dynamic language. Except
when passing stuff to Django's fields. And in JavaScript. It seems like the
thing was made to create references to `undefined`. And make them easily
convertible to numbers and strings so that our calculations mysteriously
fail when we're missing a function argument somewhere.

[toc] | [prev] | [next] | [standalone]


#46946 — Re: Bools and explicitness [was Re: PyWart: The problem with "print"]

FromJason Swails <jason.swails@gmail.com>
Date2013-06-04 13:32 -0400
SubjectRe: Bools and explicitness [was Re: PyWart: The problem with "print"]
Message-ID<mailman.2669.1370367147.3114.python-list@python.org>
In reply to#46923

[Multipart message — attachments visible in raw view] — view raw

On Tue, Jun 4, 2013 at 11:44 AM, Rick Johnson
<rantingrickjohnson@gmail.com>wrote:

>
> This implicit conversion seems like a good idea at first,
> and i was caught up in the hype myself for some time: "Hey,
> i can save a few keystrokes, AWESOME!". However, i can tell
> you with certainty that this implicit conversion is folly.
> It is my firm belief that truth testing a value that is not
> a Boolean should raise an exception. If you want to convert
> a type to Boolean then pass it to the bool function:
>
>     lst = [1,2,3]
>     if bool(lst):
>         do_something
>
> This would be "explicit enough"


i
f lst:
    do_something

is equivalent to

if bool(lst):
   do_something

why not just have your editor autobool so you can spend more time coding
and less time stamping around?  That way the person that finds booled code
more readable can have what he wants and the people that find it less
readable can have what they want.

Win-win

BTW, you should do pointless comparisons like

if condition is True:
    do_something

rather than

if condition == True
    do_something

[toc] | [prev] | [next] | [standalone]


#46947 — Re: Bools and explicitness [was Re: PyWart: The problem with "print"]

FromIan Kelly <ian.g.kelly@gmail.com>
Date2013-06-04 11:42 -0600
SubjectRe: Bools and explicitness [was Re: PyWart: The problem with "print"]
Message-ID<mailman.2670.1370367825.3114.python-list@python.org>
In reply to#46923
On Tue, Jun 4, 2013 at 9:44 AM, Rick Johnson
<rantingrickjohnson@gmail.com> wrote:
> It is my firm belief that truth testing a value that is not
> a Boolean should raise an exception. If you want to convert
> a type to Boolean then pass it to the bool function:
>
>     lst = [1,2,3]
>     if bool(lst):
>         do_something
>
> This would be "explicit enough"

That is *exactly* equivalent to the same test without the bool
function, and it gives the reader zero additional information about
what "lst" is, so it boggles me that you approve of this "if
bool(lst):" monstrosity while decrying the equivalent and slightly
more efficient "if lst:".

I think part of your complaint concerns the fact that the reader must
understand the rules by which a truth value is implicitly obtained
from lst in the statement "if lst:".  But the reader must know the
*same* rules in order to understand the more explicit "if bool(lst):",
so there is no benefit to the latter in that regard either.

> Yes i do care about the length or i would not have asked.
> I'm asking Python to tell me if the iterable has members,
> amd if it does, i want to execute a block of code, if it
> does not, i want to do nothing. But i'm also informing the
> reader of my source code that the symbol i am truth testing
> is expected to be an iterable with a __len__ method.

Caring that the object has a length is not the same as caring about
what the object's length is.  Steven's point stands, that your code
inefficiently asks the object for some property that you don't (yet)
care about.

> "if lst" does not give me the same answer (or imply the same
> meaning to a reader), it merely tells me that the implict
> conversion has resulted in a True value, but what if the lst
> symbol is pointing to a string? Then i will falsely believe
> i have a list with members when i actually have a string
> with length greater than zero.

Your "if len(lst) > 0" fails to differentiate lists from strings in
exactly the same way.

> I agree. Summing the list members just to guarantee that the
> iterable has members is foolish, however, python gives me no
> other choice IF i want to be "explicit enough". In a
> properly designed language, the base iterable object would
> supply a "hasLength" or "hasMembers" method that would
> return a much faster check of:
>
>     try:
>         iterable[0]
>     except IndexError:
>         return False
>     else:
>         return True
>
> That check would guarantee the iterable contained at least
> one member without counting them all.

You said earlier in your post that "bool(lst)" was "explicit enough",
and this is exactly what it does.

> When i am writing code i prefer to be "explicit enough" so
> that IF my assumptions about the exact type of an object are
> incorrect, the code will fail quickly enough that i can
> easily find and correct the problem.

In a duck-typing language you should not be making assumptions about
the "exact type" of an object in the first place.  If I'm writing a
function that receives a list-like argument, then at the *most
specific* I will assume that the object passed in is a MutableSequence
(but since I prefer to keep my functions functional where practical,
more usually I will assume only that the object is an iterable or a
generic sequence).  If the caller wants to pass in a deque or some
user-defined generic MutableSequence instead, then let them do so.  I
will also clearly document that assumption; if the caller can't be
bothered to read the docs and passes in an object that breaks that
assumption, then that's their own damn problem when it doesn't work.
This is a programming language for consenting adults.

> But we are really ignoring the elephant in the room. Implict
> conversion to Boolean is just a drop in the bucket compared
> to the constant "shell game" we are subjected to when
> reading source code. We so naively believe that a symbol
> named "lst" is a list object or a symbol "age" is a integer,
> when we could be totally wrong! This is the source of many
> subtle bugs!!!

I am more likely to believe that an object is a list based on the
documentation than on the mere fact that it is named "lst".  The
variable *does* have documentation, doesn't it?  If when debugging I
have reason to suspect that the documentation is incorrect or is being
ignored, then I'll add an assertion to test it.

> There must be some method by which we can truth test an
> iterable object and verify it has members, but do so in a
> manner that is valid for all types AND exposes the "expected
> type" in the method name. hmm...

This is nonsense.  If it exposes the "expected type" in the name, then
it can only be valid for that expected type.

> Adding a method like "is_valid" to every object can seem
> logical, however, this can fail just as miserably as
> Python's current implicit bool. And, more disastrously, an
> "is_valid" method is not going to raise an error (where it
> should) because it works for all types.

Actually it sounds completely illogical to me.  What would be an
"invalid" object?

> What we need is a method by which we can validate a symbol
> and simultaneously do the vaidation in a manner that will
> cast light on the type that is expected. In order for this
> to work, you would need validators with unique "type names"
>
>     if var.is_validList():
>     elif var.is_validString():
>     elif var.is_vaildTuple():
>     elif var.is_validInteger():
>     elif var.is_validFloat():
>     elif var.is_validDict():
>     etc...

How are these any different from the more flexible isinstance?  And
where exactly are you going to stop with these is_valid methods?

var.is_validObject()
var.is_validDate()
var.is_validTime()
var.is_validDatetime()
var.is_validSocket()
var.is_validDeque()
var.is_validMutableSequence()
var.is_validSequence()
var.is_validMutableSequencePlusAConcatenateMethod()
var.is_validUserDefinedObjectThatDoesNotExistInTheStandardLibraryAtAll()

And on and on and on.  How do you plan to add every single possible
one of these methods to every single object?  Remember that if you
miss one, e.g. if you leave is_validString() off of your socket
objects, then you'll get an AttributeError instead of a simple False
value when you try to test it.

> By this manner, we can roll three common tests into one
> method:
>
>     * boolean conversion
>     * member truthiness for iterables
>     * type checking

How exactly does this is_valid method perform the first two?  Are you
suggesting that an empty sequence should not be considered "valid"?

[toc] | [prev] | [next] | [standalone]


#46981 — Re: Bools and explicitness [was Re: PyWart: The problem with "print"]

FromRick Johnson <rantingrickjohnson@gmail.com>
Date2013-06-04 16:21 -0700
SubjectRe: Bools and explicitness [was Re: PyWart: The problem with "print"]
Message-ID<4bb7ce20-30c9-4d26-a11e-b0b49cc320c8@z8g2000yqd.googlegroups.com>
In reply to#46947
On Jun 4, 12:42 pm, Ian Kelly <ian.g.ke...@gmail.com> wrote:

> > By this manner, we can roll three common tests into one
> > method:
> >     * Boolean conversion
> >     * member truthiness for iterables
> >     * type checking
> How exactly does this is_valid method perform the first two?  Are you
> suggesting that an empty sequence should not be considered "valid"?

I'm suggesting that the rules for Python's current "implicit
conversion to Boolean" simply be moved into a "explicit function"
named "isvalid", that also does a type check. Here is some Python code
that might help you understand.

py> def isvalid(object_, type_):
...     if isinstance(object_, type_) and object_:
...         return True
...     return False
py> isvalid([], list)
False
py> isvalid([1], list)
True
py> isvalid(0, int)
False
py> isvalid(1, int)
True
py> isvalid({}, dict)
False
py> isvalid("", str)
False
py> isvalid(" ", str)
True

Now, let's go back to my earlier example of where i was expecting a
list but got a string instead. If i use Python's current implicit
conversion to Boolean my code will do something i don't want it to do.

py> lst = " "
py> if lst:
...     print("I'm a liar")
... else:
...     print("I'm honest")
I'm a liar

But unlike this simple example (which failed quickly) in the real
world, it may not fail for a long time. And when it does fail, you
will be pulling your hair out tracking down the origin of the bug. If
however i use my "isvalid" function, my conditional will not lie to
me:

py> lst = " "
py> if isvalid(lst, list):
...     print("I'm a liar")
... else:
...     print("I'm honest")
I'm honest

Now. You're not always going to need to "isvalid" function. Sometimes
you just need to test type, sometimes you just need convert to
Boolean, and sometimes you can just fly by the seat of your pants. The
point is, remove implicitly and inject explicitly.

Furthermore: If the current "implicit conversion to Boolean" can be
optimized by Python, then there is no reason why an explicit "isvalid"
function cannot -- any talk to the contrary is just BS.

If you still feel that this idea is garbage, then, keep on writing
your sloppy code. My proposal is the best method to handle the
problems that arise with duck typed languages in a manner that is not
restrictive or laborious -- it's actually quite elegant.

*school-bell-rings*

[toc] | [prev] | [next] | [standalone]


#46982 — Re: Bools and explicitness [was Re: PyWart: The problem with "print"]

FromMark Lawrence <breamoreboy@yahoo.co.uk>
Date2013-06-05 00:37 +0100
SubjectRe: Bools and explicitness [was Re: PyWart: The problem with "print"]
Message-ID<mailman.2690.1370389047.3114.python-list@python.org>
In reply to#46981
On 05/06/2013 00:21, Rick Johnson wrote:
[snip]

Would you be kind enough not to smoke too much wacky baccy before 
posting, thanks.

-- 
"Steve is going for the pink ball - and for those of you who are 
watching in black and white, the pink is next to the green." Snooker 
commentator 'Whispering' Ted Lowe.

Mark Lawrence

[toc] | [prev] | [next] | [standalone]


#47018 — Re: Bools and explicitness [was Re: PyWart: The problem with "print"]

FromMichael Torrie <torriem@gmail.com>
Date2013-06-04 23:28 -0600
SubjectRe: Bools and explicitness [was Re: PyWart: The problem with "print"]
Message-ID<mailman.2701.1370410128.3114.python-list@python.org>
In reply to#46981
On 06/04/2013 05:21 PM, Rick Johnson wrote:
> If you still feel that this idea is garbage, then, keep on writing
> your sloppy code. My proposal is the best method to handle the
> problems that arise with duck typed languages in a manner that is not
> restrictive or laborious -- it's actually quite elegant.

Like most of your proposals, this does not have anything to do with the
python syntax itself.  You just demonstrated code that does what you
want.  So use it then.  Adopt it in your own code, encourage others to
use it.  No changes to Python are needed.  If this technique proves its
value, then it will be adopted.  If not, it will die.  Start using it in
one of your major open source projects.

> *school-bell-rings*

It's one thing to patronize people as you try to do to D'Aprano (and yes
I admit that most replies to your posts are often patronizing to you in
return), but you do realize this infantile attempt to try to make
yourself look smarter than others really reflects poorly on you?  I for
one feel badly for you on this count, or at least embarrassed.  So just
a suggestion... drop the school bell and teacher stuff (or at least
share your qualifications with us).  It's really tiring, though to be
fair not quite as tiring as trying to help someone with an iron skull
get a CGI script working.

[toc] | [prev] | [next] | [standalone]


#47026 — Re: Bools and explicitness [was Re: PyWart: The problem with "print"]

From"Russ P." <Russ.Paielli@gmail.com>
Date2013-06-04 23:11 -0700
SubjectRe: Bools and explicitness [was Re: PyWart: The problem with "print"]
Message-ID<c70964e8-059e-4b19-b822-d54250ea2118@googlegroups.com>
In reply to#46923
On Tuesday, June 4, 2013 8:44:11 AM UTC-7, Rick Johnson wrote:

> Yes, but the problem is not "my approach", rather the lack
> 
> of proper language design (my apologizes to the "anointed
> 
> one". ;-)

If you don't like implicit conversion to Boolean, then maybe you should be using another language -- and I mean that in a constructive sense. I'm not particularly fond of it either, but I switched from Python to another language a while back. The issue is not a lack of "proper language design" but rather a language design philosophy that values conciseness and simplicity over explicitness and rigor. 

Implicit conversion to Boolean is only one of many language features that are questionable for critical production software. Another is the convention of interpreting negative indices as counting backward from the end of a list or sequence. Yeah, I thought that was elegant... until it bit me. Is it a bad idea? Not necessarily. It certainly enhances programmer productivity, and it can be done correctly "almost" all the time. But that one time in a hundred or a thousand when you accidentally use a negative index can be a bitch.

But then, what would you expect of a language that allows you to write

x = 1
x = "Hello"

It's all loosey goosey -- which is fine for many applications but certainly not for critical ones.

[toc] | [prev] | [next] | [standalone]


Page 2 of 6 — ← Prev page 1 [2] 3 4 5 6  Next page →

Back to top | Article view | comp.lang.python


csiph-web