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


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

Re: Implicit conversion to boolean in if and while statements

Started byRick Johnson <rantingrickjohnson@gmail.com>
First post2013-02-07 22:16 -0800
Last post2013-02-11 21:12 -0800
Articles 17 on this page of 57 — 11 participants

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

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: Implicit conversion to boolean in if and while statements Rick Johnson <rantingrickjohnson@gmail.com> - 2013-02-07 22:16 -0800
    Re: Implicit conversion to boolean in if and while statements Michael Torrie <torriem@gmail.com> - 2013-02-07 23:27 -0700
      Re: Implicit conversion to boolean in if and while statements Rick Johnson <rantingrickjohnson@gmail.com> - 2013-02-07 22:32 -0800
      Re: Implicit conversion to boolean in if and while statements Rick Johnson <rantingrickjohnson@gmail.com> - 2013-02-07 22:32 -0800
    Re: Implicit conversion to boolean in if and while statements Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-02-09 02:16 +1100
      Re: Implicit conversion to boolean in if and while statements Rick Johnson <rantingrickjohnson@gmail.com> - 2013-02-08 09:48 -0800
        Re: Implicit conversion to boolean in if and while statements Roy Smith <roy@panix.com> - 2013-02-08 12:58 -0500
        Re: Implicit conversion to boolean in if and while statements Rick Johnson <rantingrickjohnson@gmail.com> - 2013-02-08 11:58 -0800
          Re: Implicit conversion to boolean in if and while statements Chris Angelico <rosuav@gmail.com> - 2013-02-09 11:05 +1100
            Re: Implicit conversion to boolean in if and while statements Rick Johnson <rantingrickjohnson@gmail.com> - 2013-02-08 16:49 -0800
              Re: Implicit conversion to boolean in if and while statements Chris Angelico <rosuav@gmail.com> - 2013-02-09 12:17 +1100
                Re: Implicit conversion to boolean in if and while statements Rick Johnson <rantingrickjohnson@gmail.com> - 2013-02-09 20:54 -0800
                  Re: Implicit conversion to boolean in if and while statements Chris Angelico <rosuav@gmail.com> - 2013-02-10 16:04 +1100
                    Re: Implicit conversion to boolean in if and while statements Rick Johnson <rantingrickjohnson@gmail.com> - 2013-02-11 04:28 -0800
                      Re: Implicit conversion to boolean in if and while statements Chris Angelico <rosuav@gmail.com> - 2013-02-11 23:50 +1100
                        Re: Implicit conversion to boolean in if and while statements Rick Johnson <rantingrickjohnson@gmail.com> - 2013-02-11 05:28 -0800
                          Re: Implicit conversion to boolean in if and while statements Chris Angelico <rosuav@gmail.com> - 2013-02-12 00:52 +1100
                            Re: Implicit conversion to boolean in if and while statements Rick Johnson <rantingrickjohnson@gmail.com> - 2013-02-11 20:24 -0800
                            Re: Implicit conversion to boolean in if and while statements Rick Johnson <rantingrickjohnson@gmail.com> - 2013-02-11 20:24 -0800
                        Re: Implicit conversion to boolean in if and while statements Rick Johnson <rantingrickjohnson@gmail.com> - 2013-02-11 05:28 -0800
                    Re: Implicit conversion to boolean in if and while statements Rick Johnson <rantingrickjohnson@gmail.com> - 2013-02-11 04:28 -0800
                Re: Implicit conversion to boolean in if and while statements Rick Johnson <rantingrickjohnson@gmail.com> - 2013-02-09 20:54 -0800
              Re: Implicit conversion to boolean in if and while statements Ian Kelly <ian.g.kelly@gmail.com> - 2013-02-08 18:29 -0700
              Re: Implicit conversion to boolean in if and while statements Chris Angelico <rosuav@gmail.com> - 2013-02-09 16:01 +1100
                Re: Implicit conversion to boolean in if and while statements Rick Johnson <rantingrickjohnson@gmail.com> - 2013-02-09 20:26 -0800
                  Re: Implicit conversion to boolean in if and while statements Chris Angelico <rosuav@gmail.com> - 2013-02-10 15:50 +1100
                    Re: Implicit conversion to boolean in if and while statements Rick Johnson <rantingrickjohnson@gmail.com> - 2013-02-10 18:09 -0800
                    Re: Implicit conversion to boolean in if and while statements Rick Johnson <rantingrickjohnson@gmail.com> - 2013-02-10 18:09 -0800
                  Re: Implicit conversion to boolean in if and while statements Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-02-10 22:37 +1100
                    Re: Implicit conversion to boolean in if and while statements Roy Smith <roy@panix.com> - 2013-02-10 09:45 -0500
                    Re: Implicit conversion to boolean in if and while statements Thomas Rachel <nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915@spamschutz.glglgl.de> - 2013-02-10 18:06 +0100
                    Re: Implicit conversion to boolean in if and while statements Rick Johnson <rantingrickjohnson@gmail.com> - 2013-02-11 04:18 -0800
                      Re: Implicit conversion to boolean in if and while statements Chris Angelico <rosuav@gmail.com> - 2013-02-11 23:40 +1100
                        Re: Implicit conversion to boolean in if and while statements Rick Johnson <rantingrickjohnson@gmail.com> - 2013-02-11 05:13 -0800
                          Re: Implicit conversion to boolean in if and while statements Chris Angelico <rosuav@gmail.com> - 2013-02-12 00:35 +1100
                            Re: Implicit conversion to boolean in if and while statements Rick Johnson <rantingrickjohnson@gmail.com> - 2013-02-11 20:00 -0800
                            Re: Implicit conversion to boolean in if and while statements Rick Johnson <rantingrickjohnson@gmail.com> - 2013-02-11 20:00 -0800
                          Re: Implicit conversion to boolean in if and while statements 88888 Dihedral <dihedral88888@googlemail.com> - 2013-02-11 17:06 -0800
                            Re: Implicit conversion to boolean in if and while statements Chris Angelico <rosuav@gmail.com> - 2013-02-12 16:55 +1100
                              Re: Implicit conversion to boolean in if and while statements Rick Johnson <rantingrickjohnson@gmail.com> - 2013-02-12 09:48 -0800
                                Re: Implicit conversion to boolean in if and while statements Chris Angelico <rosuav@gmail.com> - 2013-02-13 08:24 +1100
                                Re: Implicit conversion to boolean in if and while statements 88888 Dihedral <dihedral88888@googlemail.com> - 2013-02-12 18:43 -0800
                                Re: Implicit conversion to boolean in if and while statements 88888 Dihedral <dihedral88888@googlemail.com> - 2013-02-12 18:43 -0800
                                Re: Implicit conversion to boolean in if and while statements Ian Kelly <ian.g.kelly@gmail.com> - 2013-02-15 13:12 -0700
                                Re: Implicit conversion to boolean in if and while statements Chris Angelico <rosuav@gmail.com> - 2013-02-16 11:12 +1100
                              Re: Implicit conversion to boolean in if and while statements Rick Johnson <rantingrickjohnson@gmail.com> - 2013-02-12 09:48 -0800
                          Re: Implicit conversion to boolean in if and while statements 88888 Dihedral <dihedral88888@googlemail.com> - 2013-02-11 17:06 -0800
                        Re: Implicit conversion to boolean in if and while statements Rick Johnson <rantingrickjohnson@gmail.com> - 2013-02-11 05:13 -0800
                    Re: Implicit conversion to boolean in if and while statements Serhiy Storchaka <storchaka@gmail.com> - 2013-02-15 21:09 +0200
                Re: Implicit conversion to boolean in if and while statements Rick Johnson <rantingrickjohnson@gmail.com> - 2013-02-09 20:26 -0800
            Re: Implicit conversion to boolean in if and while statements Rick Johnson <rantingrickjohnson@gmail.com> - 2013-02-08 16:49 -0800
          Re: Implicit conversion to boolean in if and while statements Ian Kelly <ian.g.kelly@gmail.com> - 2013-02-08 18:06 -0700
            Re: Implicit conversion to boolean in if and while statements Rick Johnson <rantingrickjohnson@gmail.com> - 2013-02-09 22:25 -0800
            Re: Implicit conversion to boolean in if and while statements Rick Johnson <rantingrickjohnson@gmail.com> - 2013-02-09 22:25 -0800
        Re: Implicit conversion to boolean in if and while statements Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-02-09 14:16 +1100
          Re: Implicit conversion to boolean in if and while statements Dennis Lee Bieber <wlfraed@ix.netcom.com> - 2013-02-09 15:36 -0500
        Re: Implicit conversion to boolean in if and while statements Mark Janssen <dreamingforward@gmail.com> - 2013-02-11 21:12 -0800

Page 3 of 3 — ← Prev page 1 2 [3]


#38787

FromChris Angelico <rosuav@gmail.com>
Date2013-02-13 08:24 +1100
Message-ID<mailman.1728.1360704273.2939.python-list@python.org>
In reply to#38774
On Wed, Feb 13, 2013 at 4:48 AM, Rick Johnson
<rantingrickjohnson@gmail.com> wrote:
> Your confusion may stem from interpreting "constant" as the CS term "CONSTANT"[1]; whereby the objects in the tuple are programming CONSTANTS, that is, unable to change.

Uhh, yeah. Not being Humpty Dumpty, I interpret "constants" to mean
"things that won't change". (Or, eliding the second t, as "I've found
a friend". But I digress.) There's just something about that word
"constant" that really suggests a meaning of "constant".

ChrisA

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


#38798

From88888 Dihedral <dihedral88888@googlemail.com>
Date2013-02-12 18:43 -0800
Message-ID<19bb1c74-8b2c-4265-9b82-1b88d4906f91@googlegroups.com>
In reply to#38774
Rick Johnson於 2013年2月13日星期三UTC+8上午1時48分07秒寫道:
> On Monday, February 11, 2013 11:55:19 PM UTC-6, Chris Angelico wrote:
> 
> > On Tue, Feb 12, 2013 at 12:06 PM, 88888 Dihedral wrote:
> 
> > > A permanently mutated list is a tuple of constant objects.
> 
> >
> 
> > I nominate this line as "bemusing head-scratcher of the week".
> 
> 
> 
> Actually the statement is fact IF you can grok it through the eyes of clarity.
> 
> 
> 
> "A permanently mutated list..."
> 
> 
> 
> A list that has been mutated permanently, that is, it cannot be changed back into a list. psst: i have a sneaking suspicion that he his referring to tuples, let's see.
> 
> 
> 
> "...is a tuple..."
> 
> 
> 
> Ha! Well in Python the immutable sequence type /is/ a tuple after all.
> 
> 
> 
> "...of constant objects..."
> 
> 
> 
> The tuple contains objects, and it's objects will maintain a constant ordering (relatively in tuple structure) until until the tuple's death. 
> 
> 

>>> a1=[1,2,3]
>>> tuple1=(a1,4,5,6)
>>> tuple1
([1, 2, 3], 4, 5, 6)
>>> a1=[1,2]
>>> tuple1
([1, 2, 3], 4, 5, 6)
>>> 

Yes, a tuple of constant objects is still not clear. 


> 
> Your confusion may stem from interpreting "constant" as the CS term "CONSTANT"[1]; whereby the objects in the tuple are programming CONSTANTS, that is, unable to change. But in reality, although a tuple (bka:StaticList) cannot expand to add more objects, or shrink to eject existing objects, the objects themselves CAN change their own internal state WITHOUT disrupting the immutable harmony of the tuple. 
> 
> 
> 
> Observe:
> 
>     
> 
> py> class Foo(object):
> 
> 	pass
> 
> py> foo = Foo()
> 
> py> t = (1,'1', foo)
> 
> py> t
> 
> (1, '1', <__main__.Foo object at 0x0267BF50>)
> 
> py> t[-1].bar = "abc"
> 
> py> t
> 
> (1, '1', <__main__.Foo object at 0x0267BF50>)
> 
> 
> 
> Or by expanding a list
> 
> 
> 
> py> t = (1,2,3)
> 
> py> t = t+([],)
> 
> py> t
> 
> (1, 2, 3, [])
> 
> py> t[-1].append('circus')
> 
> py> t
> 
> (1, 2, 3, ['circus'])
> 
> 
> 
> [1] Which is an unfortunate side-effect of polysemy and compounded exponentially by naive (and sometimes a purely malevolent intent when) transformation of words into esoteric problem domains.

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


#38799

From88888 Dihedral <dihedral88888@googlemail.com>
Date2013-02-12 18:43 -0800
Message-ID<mailman.1732.1360723431.2939.python-list@python.org>
In reply to#38774
Rick Johnson於 2013年2月13日星期三UTC+8上午1時48分07秒寫道:
> On Monday, February 11, 2013 11:55:19 PM UTC-6, Chris Angelico wrote:
> 
> > On Tue, Feb 12, 2013 at 12:06 PM, 88888 Dihedral wrote:
> 
> > > A permanently mutated list is a tuple of constant objects.
> 
> >
> 
> > I nominate this line as "bemusing head-scratcher of the week".
> 
> 
> 
> Actually the statement is fact IF you can grok it through the eyes of clarity.
> 
> 
> 
> "A permanently mutated list..."
> 
> 
> 
> A list that has been mutated permanently, that is, it cannot be changed back into a list. psst: i have a sneaking suspicion that he his referring to tuples, let's see.
> 
> 
> 
> "...is a tuple..."
> 
> 
> 
> Ha! Well in Python the immutable sequence type /is/ a tuple after all.
> 
> 
> 
> "...of constant objects..."
> 
> 
> 
> The tuple contains objects, and it's objects will maintain a constant ordering (relatively in tuple structure) until until the tuple's death. 
> 
> 

>>> a1=[1,2,3]
>>> tuple1=(a1,4,5,6)
>>> tuple1
([1, 2, 3], 4, 5, 6)
>>> a1=[1,2]
>>> tuple1
([1, 2, 3], 4, 5, 6)
>>> 

Yes, a tuple of constant objects is still not clear. 


> 
> Your confusion may stem from interpreting "constant" as the CS term "CONSTANT"[1]; whereby the objects in the tuple are programming CONSTANTS, that is, unable to change. But in reality, although a tuple (bka:StaticList) cannot expand to add more objects, or shrink to eject existing objects, the objects themselves CAN change their own internal state WITHOUT disrupting the immutable harmony of the tuple. 
> 
> 
> 
> Observe:
> 
>     
> 
> py> class Foo(object):
> 
> 	pass
> 
> py> foo = Foo()
> 
> py> t = (1,'1', foo)
> 
> py> t
> 
> (1, '1', <__main__.Foo object at 0x0267BF50>)
> 
> py> t[-1].bar = "abc"
> 
> py> t
> 
> (1, '1', <__main__.Foo object at 0x0267BF50>)
> 
> 
> 
> Or by expanding a list
> 
> 
> 
> py> t = (1,2,3)
> 
> py> t = t+([],)
> 
> py> t
> 
> (1, 2, 3, [])
> 
> py> t[-1].append('circus')
> 
> py> t
> 
> (1, 2, 3, ['circus'])
> 
> 
> 
> [1] Which is an unfortunate side-effect of polysemy and compounded exponentially by naive (and sometimes a purely malevolent intent when) transformation of words into esoteric problem domains.

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


#38957

FromIan Kelly <ian.g.kelly@gmail.com>
Date2013-02-15 13:12 -0700
Message-ID<mailman.1844.1360959203.2939.python-list@python.org>
In reply to#38774
On Tue, Feb 12, 2013 at 10:48 AM, Rick Johnson
<rantingrickjohnson@gmail.com> wrote:
> On Monday, February 11, 2013 11:55:19 PM UTC-6, Chris Angelico wrote:
>> On Tue, Feb 12, 2013 at 12:06 PM, 88888 Dihedral wrote:
>> > A permanently mutated list is a tuple of constant objects.
>>
>> I nominate this line as "bemusing head-scratcher of the week".
>
> Actually the statement is fact IF you can grok it through the eyes of clarity.
>
> "A permanently mutated list..."
>
> A list that has been mutated permanently, that is, it cannot be changed back into a list. psst: i have a sneaking suspicion that he his referring to tuples, let's see.

FYI, the general consensus here is that "he" (88888 Dihedral) is a
bot.  It posts in non sequiturs and fails to respond meaningfully to
direct queries.  A few months ago I posed an obvious Turing test for
it, which it failed.

http://thread.gmane.org/gmane.comp.python.general/718489

Your naive effort to extort meaning from its nonsense is admirable, however.

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


#38981

FromChris Angelico <rosuav@gmail.com>
Date2013-02-16 11:12 +1100
Message-ID<mailman.1864.1360973561.2939.python-list@python.org>
In reply to#38774
On Sat, Feb 16, 2013 at 7:12 AM, Ian Kelly <ian.g.kelly@gmail.com> wrote:
> FYI, the general consensus here is that "he" (88888 Dihedral) is a
> bot.  It posts in non sequiturs and fails to respond meaningfully to
> direct queries.  A few months ago I posed an obvious Turing test for
> it, which it failed.
>
> http://thread.gmane.org/gmane.comp.python.general/718489

Which, I might add, was something awesome. I find Dihedral pretty
amusing, tbh... "permanently mutated list" is an interesting concept.

ChrisA

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


#38777

FromRick Johnson <rantingrickjohnson@gmail.com>
Date2013-02-12 09:48 -0800
Message-ID<mailman.1720.1360694030.2939.python-list@python.org>
In reply to#38731
On Monday, February 11, 2013 11:55:19 PM UTC-6, Chris Angelico wrote:
> On Tue, Feb 12, 2013 at 12:06 PM, 88888 Dihedral wrote:
> > A permanently mutated list is a tuple of constant objects.
>
> I nominate this line as "bemusing head-scratcher of the week".

Actually the statement is fact IF you can grok it through the eyes of clarity.

"A permanently mutated list..."

A list that has been mutated permanently, that is, it cannot be changed back into a list. psst: i have a sneaking suspicion that he his referring to tuples, let's see.

"...is a tuple..."

Ha! Well in Python the immutable sequence type /is/ a tuple after all.

"...of constant objects..."

The tuple contains objects, and it's objects will maintain a constant ordering (relatively in tuple structure) until until the tuple's death. 

Your confusion may stem from interpreting "constant" as the CS term "CONSTANT"[1]; whereby the objects in the tuple are programming CONSTANTS, that is, unable to change. But in reality, although a tuple (bka:StaticList) cannot expand to add more objects, or shrink to eject existing objects, the objects themselves CAN change their own internal state WITHOUT disrupting the immutable harmony of the tuple. 

Observe:
    
py> class Foo(object):
	pass
py> foo = Foo()
py> t = (1,'1', foo)
py> t
(1, '1', <__main__.Foo object at 0x0267BF50>)
py> t[-1].bar = "abc"
py> t
(1, '1', <__main__.Foo object at 0x0267BF50>)

Or by expanding a list

py> t = (1,2,3)
py> t = t+([],)
py> t
(1, 2, 3, [])
py> t[-1].append('circus')
py> t
(1, 2, 3, ['circus'])

[1] Which is an unfortunate side-effect of polysemy and compounded exponentially by naive (and sometimes a purely malevolent intent when) transformation of words into esoteric problem domains.

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


#38713

From88888 Dihedral <dihedral88888@googlemail.com>
Date2013-02-11 17:06 -0800
Message-ID<mailman.1674.1360631186.2939.python-list@python.org>
In reply to#38677
Rick Johnson於 2013年2月11日星期一UTC+8下午9時13分58秒寫道:
> On Monday, February 11, 2013 6:40:23 AM UTC-6, Chris Angelico wrote:
> 
> > [...]
> 
> > Or doing what you were pointing and laughing at Pike for, and using
> 
> > two-symbol delimiters. You could even make it majorly logical:
> 
> > 
> 
> > list_ = [[ 1, 2, 3 ]]
> 
> > tuple_ = ([ 1, 2, 3 ])
> 
> > dict_ = [{ 1, 2, 3 }]
> 
> > frozendict_ = ({ 1, 2, 3 })
> 
> > set_ = [< 1, 2, 3 >]
> 
> > frozenset_ = (< 1, 2, 3 >)
> 
> 
> 
> I am vehemently against using more than one "opening seq char" and one "closing seq char". It works fine for single depth sequences, however, once you start nesting the mental focus required to parse the doubled openers/closers is headache inducing. I would accept wrapping the literal in some sort of declaration though, something like i proposed earlier in the thread. The easiest is to use:
> 
> 
> 
>   set({1,2,3})
> 
> 
> 
> but that looks like a function call! So we'd need a unique syntax. Either a single tag like:
> 
> 
> 
>   set{1,2,3}
> 
> 
> 
> Or we could use start and end tags like:
> 
> 
> 
>   set{1,2,3}set
> 
> 
> 
> where "set{" and "}set" are delimiters. For lists, tuples, and dict we would use the short form because these literals are far too ubiquitous:
> 
> 
> 
>   [1,2,3] # list
> 
>   {k:v} # dict
> 
>   (1,2,3) # tuple
> 
> 
> 
> However, the grouping chars for tuples has always been confusing because they can clash with grouping of expressions. What is this?
> 
> 
> 
>   (1)
> 
> 
> 
> It's NOT a tuple! But it looks like a tuple! What is this:
> 
> 
> 
>   1,2
> 
> 
> 
> it IS a tuple, but it does not look like a tuple! 
> 
> 
> 
> That's an unfortunate side effect of a poorly thought-out tuple syntax.

I am thinking a mutated list temporarily is useful when a list is to be used 
to be iterated through all of its elements efficiently.

A permanently mutated list is a tuple of constant objects.

As for the set type, I prefer to use the operations of the list,
dictionaries in Python to act for the designed purposes. 

 




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


#38678

FromRick Johnson <rantingrickjohnson@gmail.com>
Date2013-02-11 05:13 -0800
Message-ID<mailman.1646.1360588449.2939.python-list@python.org>
In reply to#38671
On Monday, February 11, 2013 6:40:23 AM UTC-6, Chris Angelico wrote:
> [...]
> Or doing what you were pointing and laughing at Pike for, and using
> two-symbol delimiters. You could even make it majorly logical:
> 
> list_ = [[ 1, 2, 3 ]]
> tuple_ = ([ 1, 2, 3 ])
> dict_ = [{ 1, 2, 3 }]
> frozendict_ = ({ 1, 2, 3 })
> set_ = [< 1, 2, 3 >]
> frozenset_ = (< 1, 2, 3 >)

I am vehemently against using more than one "opening seq char" and one "closing seq char". It works fine for single depth sequences, however, once you start nesting the mental focus required to parse the doubled openers/closers is headache inducing. I would accept wrapping the literal in some sort of declaration though, something like i proposed earlier in the thread. The easiest is to use:

  set({1,2,3})

but that looks like a function call! So we'd need a unique syntax. Either a single tag like:

  set{1,2,3}

Or we could use start and end tags like:

  set{1,2,3}set

where "set{" and "}set" are delimiters. For lists, tuples, and dict we would use the short form because these literals are far too ubiquitous:

  [1,2,3] # list
  {k:v} # dict
  (1,2,3) # tuple

However, the grouping chars for tuples has always been confusing because they can clash with grouping of expressions. What is this?

  (1)

It's NOT a tuple! But it looks like a tuple! What is this:

  1,2

it IS a tuple, but it does not look like a tuple! 

That's an unfortunate side effect of a poorly thought-out tuple syntax. 

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


#38949

FromSerhiy Storchaka <storchaka@gmail.com>
Date2013-02-15 21:09 +0200
Message-ID<mailman.1837.1360955401.2939.python-list@python.org>
In reply to#38566
On 10.02.13 13:37, Steven D'Aprano wrote:
> Unfortunately, Python has a minor design flaw. One of the most common
> use-cases for sets is for membership testing of literal sets:
> 
> def example(arg):
>      if arg in {'spam', 'ham', 'eggs', 'cheese'}:
>          ...
> 
> Unfortunately, set literals create *mutable* sets, not frozensets. That
> means that the compiler wastes time and memory creating am over-allocated
> mutable set object. If set literals created immutable frozensets, there
> would be some nice opportunities for the compiler to optimize this
> use-case.

CPython 3.2 optimizes this special case and creates a constant frozenset.

$ echo "arg in {'spam', 'ham', 'eggs', 'cheese'}" | python3.2 -m dis -
  1           0 LOAD_NAME                0 (arg) 
              3 LOAD_CONST               5 (frozenset({'cheese', 'eggs', 'ham', 'spam'})) 
              6 COMPARE_OP               6 (in) 
              9 POP_TOP              
             10 LOAD_CONST               4 (None) 
             13 RETURN_VALUE         

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


#38551

FromRick Johnson <rantingrickjohnson@gmail.com>
Date2013-02-09 20:26 -0800
Message-ID<mailman.1569.1360470388.2939.python-list@python.org>
In reply to#38498
On Friday, February 8, 2013 11:01:00 PM UTC-6, Chris Angelico wrote:
> [...]
> Another advantage of using two characters: There's no conflict between
> set and dict literals. How do you notate an empty set in Python? {}
> means an empty dict.

What makes you believe that a language must provide literal syntax for EACH and EVERY type? And BTW, if you don't already know, this is how you notate an empty set in Python:

py> set([])
set([])

IMO "Set Types" should only exists as a concequence of "freezing" an array, and should have NO literal syntax avaiable.

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


#38484

FromRick Johnson <rantingrickjohnson@gmail.com>
Date2013-02-08 16:49 -0800
Message-ID<mailman.1523.1360370952.2939.python-list@python.org>
In reply to#38481
On Friday, February 8, 2013 6:05:54 PM UTC-6, Chris Angelico wrote:
> The sum builtin works happily on any sequence of objects
> that can be added together. It works as an excellent
> flatten() method:
> 
> >>> nested_list = [["q"], ["w","e"], ["r","t","u"], ["i","o","p"]]
> >>> sum(nested_list,[])
> ['q', 'w', 'e', 'r', 't', 'u', 'i', 'o', 'p']
> >>> nested_list
> [['q'], ['w', 'e'], ['r', 't', 'u'], ['i', 'o', 'p']]

What the hell? Oh yeah, you must be using pike again. No, if it were pike the list would look like this:

({({"q"}), ({"w","e"}), ({"r","t","u"}), ({"i","o","p"})})

Of course you'd have to declare it first using an /expanded/ Java syntax:

 nested_list = array(array(string))
 
Folks, i couldn't make this stuff up if i wanted to. Go read for yourself if want a few laughs.
  
  http://pike.lysator.liu.se/docs/tutorial/data_types/container_types.xml

> I'm not sure what your definition of a numeric type is, but I suspect
> that list(str) isn't part of it.

Of course not. 

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


#38486

FromIan Kelly <ian.g.kelly@gmail.com>
Date2013-02-08 18:06 -0700
Message-ID<mailman.1525.1360372044.2939.python-list@python.org>
In reply to#38476
On Fri, Feb 8, 2013 at 12:58 PM, Rick Johnson
<rantingrickjohnson@gmail.com> wrote:
> I'm a bit unnerved by the sum function. Summing a sequence only makes sense if the sequence in question contains /only/ numeric types. For that reason i decided to create a special type for holding Numerics. This will probably result in many complaints from lazy people who want to use only one Sequence type, which holds mixed types, THEN jamb nothing but numeric types into it, THEN have a sum method that throws errors when it encounters a non-numeric type!!! I say, too bad for you.
>
> Stop obfuscating your code! Of course someone could probably find a legitimate reason to apply a sum method to non-numeric values; if so, then inherit from NumericSequence and create your custom type!

Are you aware that the approach you're advocating here is bad OOP
design?  If you declare a class NumericSequence with the property that
it contains only numeric types, and then you declare a subclass
NonnumericSequence that does not share that property, then guess what?
 You've just violated the Liskov Substitution Principle.

The goal you're trying to achieve here is nonsensical anyway.  Ask
yourself what the semantic meaning of the sum() function is, what
purpose it is meant to serve.  My answer: it is the reduction of the
addition operator.  The implication of this is that the input type of
the sum() function is not "numbers", but rather "things that can be
added".  That includes numbers, but since I see from your proposed
class hierarchy that you are retaining the __add__ method on
sequences, it also includes sequences.  Are you really going to tell
the user that (1, 2, 3) + (4, 5, 6) is perfectly fine, but that the
semantic equivalent sum([(1, 2, 3), (4, 5, 6)]) is nonsense?

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


#38557

FromRick Johnson <rantingrickjohnson@gmail.com>
Date2013-02-09 22:25 -0800
Message-ID<387eb674-d2c7-43f0-9490-6ac6861965b9@googlegroups.com>
In reply to#38486
On Friday, February 8, 2013 7:06:34 PM UTC-6, Ian wrote:
> On Fri, Feb 8, 2013 at 12:58 PM, Rick Johnson
>  wrote:
> > I'm a bit unnerved by the sum function. Summing a
> > sequence only makes sense if the sequence in question
> > contains /only/ numeric types. For that reason i decided
> > to create a special type for holding Numerics.
> > [...]
> > Of course someone could
> > probably find a legitimate reason to apply a sum method
> > to non-numeric values; if so, then inherit from
> > NumericSequence and create your custom type!
>
> Are you aware that the approach you're advocating here is bad OOP
> design?  If you declare a class NumericSequence with the property that
> it contains only numeric types, and then you declare a subclass
> NonnumericSequence that does not share that property, then guess what?
> You've just violated the Liskov Substitution Principle.

I totally agree! Really, no sarcasm here O:-)

Not only because we would be attempting to bend a numeric type into something it is not, but even more foolishly because the very method we hope to gain (sum) would need to be completely re-written anyway. I must have lost myself in the rant because that was a foolish thing to say. Thanks for pointing this out.

> The goal you're trying to achieve here is nonsensical anyway.  Ask
> yourself what the semantic meaning of the sum() function is, what
> purpose it is meant to serve.  My answer: it is the reduction of the
> addition operator.

I think that for Numeric Types your answer is spot on! And i'll bet if we ruminated long enough we could probably find a few more transformations of the word "sum" into unique contexts. But i digress, we'll have to save that synergy for a time when you are buying the beer! ;-)

> The implication of this is that the input type of
> the sum() function is not "numbers", but rather "things that can be
> added".

Indeed. Contrary to what a few folks have stated in this thread, if two different objects have methods named "sum", that does NOT mean that we have broken the fine principles of "code reuse", no. Why? Because two methods named "sum" can contain completely different code! Yes, i know that's difficult for some to believe, but it's the truth!

Consider a sum method of a "Numeric Type" compared to the sum method of a "Sequence Type". Not only is the algorithm different, but the result is different. Summing N numerics requires utilizing the strict rules of mathematical addition, keeping a running total, and returning a type (Integer) that is different from the input type, whereas summing sequences requires expanding the first sequence with the values of the second sequence (all whilst maintaining linear order) and returning a new instance of the same type (f.e. list). 

Of course you could write a single monolithic function that can operate on multiple types transparently (*cough* saum!) however:

 * Nobody can predict the future (at least not yet) so you
   will eventually encounter a new type that breaks the
   god @#$% function.

 * Your language will rely on "magic", thereby confusing
   it's users, with well, magic!

 * But most disappointing of all: you will break the accepted
   OOP convention of encapsulation, whereby the object
   /itself/ should operate on the data, not some outside god
   @#$% function!

But let's dig a little deeper here so we might understand /why/ encapsulation is /so/ gawd @#$%ed important to OOP. 

Why do we prefer objects to operate on their own data rather than some "magical-all-knowing-god-like-creature-from-another-planet-who-thinks-his-bowel-movements-smell-like-bakery-fresh-cinnamon-rolls? Is it because we want objects to feel a sense of "belonging" or "importance"? ...OF COURSE NOT! Objects neither think nor feel!

We employ encapsulation because by doing so we keep all the relevant code under one class, one module, one package. By doing so we create a hierarchy; and since hierarchies are much easier to search than random sequences, we will thank ourselves later!

If you want a fine example of this consider a list and a dict object. If you want to find a value in a list you are forced to search the entire list "item-by-item" until you find a match; there are NO shortcuts here! However, when we have data in a dict all we need is a key, and voila!, we have a direct path to the item! Same applies to code.

RR: "GOOD paradigms solve problems when /writing/ code, GREAT paradigms solve problems when writing and /maintaining/ code!"

> That includes numbers, but since I see from your proposed
> class hierarchy that you are retaining the __add__ method on
> sequences, it also includes sequences.  Are you really going to tell
> the user that (1, 2, 3) + (4, 5, 6) is perfectly fine, but that the
> semantic equivalent sum([(1, 2, 3), (4, 5, 6)]) is nonsense?

Yes. Because if the user has a problem understanding /why/ adding two sequences together results in a new sequence and /not/ a number, he can simply open the source for the Sequence object, locate the sum method, and read code that is ONLY RELEVANT TO SUMMING A SEQUENCE OBJECT. [1]

Whereas with a global function --which has been whored-out to operate on many types, and will probably include a massive conditional!-- he will need to read through many lines of irrelevant code just to find the relevant code, then /hopefully/ he has the cognitive power remaining to find the answer.

[1] Of course this is not the /only/ reason why encapsulation is so important.

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


#38558

FromRick Johnson <rantingrickjohnson@gmail.com>
Date2013-02-09 22:25 -0800
Message-ID<mailman.1574.1360477564.2939.python-list@python.org>
In reply to#38486
On Friday, February 8, 2013 7:06:34 PM UTC-6, Ian wrote:
> On Fri, Feb 8, 2013 at 12:58 PM, Rick Johnson
>  wrote:
> > I'm a bit unnerved by the sum function. Summing a
> > sequence only makes sense if the sequence in question
> > contains /only/ numeric types. For that reason i decided
> > to create a special type for holding Numerics.
> > [...]
> > Of course someone could
> > probably find a legitimate reason to apply a sum method
> > to non-numeric values; if so, then inherit from
> > NumericSequence and create your custom type!
>
> Are you aware that the approach you're advocating here is bad OOP
> design?  If you declare a class NumericSequence with the property that
> it contains only numeric types, and then you declare a subclass
> NonnumericSequence that does not share that property, then guess what?
> You've just violated the Liskov Substitution Principle.

I totally agree! Really, no sarcasm here O:-)

Not only because we would be attempting to bend a numeric type into something it is not, but even more foolishly because the very method we hope to gain (sum) would need to be completely re-written anyway. I must have lost myself in the rant because that was a foolish thing to say. Thanks for pointing this out.

> The goal you're trying to achieve here is nonsensical anyway.  Ask
> yourself what the semantic meaning of the sum() function is, what
> purpose it is meant to serve.  My answer: it is the reduction of the
> addition operator.

I think that for Numeric Types your answer is spot on! And i'll bet if we ruminated long enough we could probably find a few more transformations of the word "sum" into unique contexts. But i digress, we'll have to save that synergy for a time when you are buying the beer! ;-)

> The implication of this is that the input type of
> the sum() function is not "numbers", but rather "things that can be
> added".

Indeed. Contrary to what a few folks have stated in this thread, if two different objects have methods named "sum", that does NOT mean that we have broken the fine principles of "code reuse", no. Why? Because two methods named "sum" can contain completely different code! Yes, i know that's difficult for some to believe, but it's the truth!

Consider a sum method of a "Numeric Type" compared to the sum method of a "Sequence Type". Not only is the algorithm different, but the result is different. Summing N numerics requires utilizing the strict rules of mathematical addition, keeping a running total, and returning a type (Integer) that is different from the input type, whereas summing sequences requires expanding the first sequence with the values of the second sequence (all whilst maintaining linear order) and returning a new instance of the same type (f.e. list). 

Of course you could write a single monolithic function that can operate on multiple types transparently (*cough* saum!) however:

 * Nobody can predict the future (at least not yet) so you
   will eventually encounter a new type that breaks the
   god @#$% function.

 * Your language will rely on "magic", thereby confusing
   it's users, with well, magic!

 * But most disappointing of all: you will break the accepted
   OOP convention of encapsulation, whereby the object
   /itself/ should operate on the data, not some outside god
   @#$% function!

But let's dig a little deeper here so we might understand /why/ encapsulation is /so/ gawd @#$%ed important to OOP. 

Why do we prefer objects to operate on their own data rather than some "magical-all-knowing-god-like-creature-from-another-planet-who-thinks-his-bowel-movements-smell-like-bakery-fresh-cinnamon-rolls? Is it because we want objects to feel a sense of "belonging" or "importance"? ...OF COURSE NOT! Objects neither think nor feel!

We employ encapsulation because by doing so we keep all the relevant code under one class, one module, one package. By doing so we create a hierarchy; and since hierarchies are much easier to search than random sequences, we will thank ourselves later!

If you want a fine example of this consider a list and a dict object. If you want to find a value in a list you are forced to search the entire list "item-by-item" until you find a match; there are NO shortcuts here! However, when we have data in a dict all we need is a key, and voila!, we have a direct path to the item! Same applies to code.

RR: "GOOD paradigms solve problems when /writing/ code, GREAT paradigms solve problems when writing and /maintaining/ code!"

> That includes numbers, but since I see from your proposed
> class hierarchy that you are retaining the __add__ method on
> sequences, it also includes sequences.  Are you really going to tell
> the user that (1, 2, 3) + (4, 5, 6) is perfectly fine, but that the
> semantic equivalent sum([(1, 2, 3), (4, 5, 6)]) is nonsense?

Yes. Because if the user has a problem understanding /why/ adding two sequences together results in a new sequence and /not/ a number, he can simply open the source for the Sequence object, locate the sum method, and read code that is ONLY RELEVANT TO SUMMING A SEQUENCE OBJECT. [1]

Whereas with a global function --which has been whored-out to operate on many types, and will probably include a massive conditional!-- he will need to read through many lines of irrelevant code just to find the relevant code, then /hopefully/ he has the cognitive power remaining to find the answer.

[1] Of course this is not the /only/ reason why encapsulation is so important.

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


#38493

FromSteven D'Aprano <steve+comp.lang.python@pearwood.info>
Date2013-02-09 14:16 +1100
Message-ID<5115bfac$0$29999$c3e8da3$5496439d@news.astraweb.com>
In reply to#38469
Rick Johnson wrote:

> On Friday, February 8, 2013 9:16:42 AM UTC-6, Steven D'Aprano wrote:
>> Rick Johnson wrote:
>>
>> > GvR has always been reluctant to incorporate full OOP machinery for
>> > some reason.
>>
>> Python is a fully object oriented language. It is *more* object oriented
>> than, say, Java.
> 
> Oh really? *chuckles*

Yes, really.


>> - everything in Python is an object, there is no distinction between
>> "boxed" and "unboxed" variables;
> 
> Just because /everything/ in Python is an object does not mean that Python
> is 100% OOP. This fact is just one of the many attributes of a 100% OOP
> language.

The essential features of OOP style are:

- dynamic dispatch -– Python has this

- encapsulation and/or multi-methods -- Python has this

- subtype polymorphism -- Python has this

- object inheritance or delegation -- Python has both of these

- open recursion (a special variable or keyword, normally called "this"
or "self", that allows method bodies to invoke another method of the same
object -- Python has this

- abstraction -- Python has this

http://en.wikipedia.org/wiki/Object-oriented_programming#Fundamental_features_and_concepts


What does not matter is syntax. Whether you write:

object#method           (OCaml)
object->method          (C++, Perl, PHP (non-static methods))
object::method          (PHP (static methods))
object <- method        (E)
[object method]         (Objective C)
object:method           (Lua)
object.method           (Java, Python, VisualBasic)
object method           (Smalltalk, some OOP dialects of Forth)
method object           (Other OOP dialects of Forth)
object \ method         (Pountain Forth)
method(object)          (Ada, Dylan, Matlab)
send method to object   (Hypertalk, OpenXION)


or something else even more exotic, is entirely irrelevant. What matters is
behaviour, not syntax.



>> Although Python is fully object-oriented, it does not insist on one
>> particular style of object syntax. It allows procedural and functional
>> style syntax as well.
> 
> Well you just defeated yourself. How can Python be 100% OOP and then allow
> other paradigms?

Your reading comprehension is lacking.

Python allows procedural and functional STYLE syntax. It does not force you
to use a dot out of some slavish attention to an artificial philosophy of
programming language:

http://steve-yegge.blogspot.com.au/2006/03/execution-in-kingdom-of-nouns.html

Python is pragmatic and human-centric. When OOP syntax is best, it will use
OOP syntax. If functional syntax is best, it will wrap objects in a thin
functional layer and use that. If procedural syntax is best, it will use
procedural-style coding. Where a pipeline or flow-based paradigm is best,
Python gives you iterators such as generator expressions. Most of the major
programming paradigms are available in Python, wrapped around a core that
is entirely objects.


>> In Python today, any() and all() will work perfectly on ANY ITERABLE
>> OBJECT, for free. The developer of that object doesn't need to do
>> anything to support any() and all(), all she has to do is make it
>> iterable.
>> 
>> Under your suggestion, every iterable object has to implement an any()
>> method, and an all() method. Every iterable type has to repeat the same
>> old code as every other iterable type.
> 
> NOT IF PYTHON WERE TRULY 100% OOP!
> 
> If so, Python would have a supertype called "Collection" that wold define
> all methods that operate on collections. Some of these include:
> 
>  len, any, all, length, isempty, __getitem__, __setitem__, etc...
>  
> Then any collection subtype would inherit from this supertype and get the
> methods for free.

No they wouldn't. They would inherit an abstract method that raises an
error "Abstract method must be overridden by the subclass" for free.

Do you really think that *every* collection's __getitem__ could possibly use
the *same* implementation?

Should frozenset and set share the same __setitem__?

And what about objects which are not *collections*, and so cannot inherit
from Collection, but still need to implement some of those methods? Strings
are not collections. Should generators be forced to inherit __setitem__ so
that they can share any() and all() methods with lists? What length()
should a lazy generator expression return?

[...]
> Using built-in functions to operate on objects is foolish because you are
> placing extra burden on the programmer to know which /functions/ work with
> which /types/. The *only* functions that should be global are the kind
> that will work on *ANY* object. But then again, the Object type could hold
> these methods!

If you can remember that lists have a sort() method and floats don't, then
you can remember that sorted() works on lists but not floats.



-- 
Steven

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


#38539

FromDennis Lee Bieber <wlfraed@ix.netcom.com>
Date2013-02-09 15:36 -0500
Message-ID<mailman.1563.1360442193.2939.python-list@python.org>
In reply to#38493
On Sat, 09 Feb 2013 14:16:59 +1100, Steven D'Aprano
<steve+comp.lang.python@pearwood.info> declaimed the following in
gmane.comp.python.general:

	Just for completeness (or, at least, fullness if not completeness)

> 
> What does not matter is syntax. Whether you write:
> 
> object#method           (OCaml)
> object->method          (C++, Perl, PHP (non-static methods))
> object::method          (PHP (static methods))
> object <- method        (E)
> [object method]         (Objective C)
> object:method           (Lua)
> object.method           (Java, Python, VisualBasic)
> object method           (Smalltalk, some OOP dialects of Forth)
> method object           (Other OOP dialects of Forth)
> object \ method         (Pountain Forth)
> method(object)          (Ada, Dylan, Matlab)

	Ada 2005 added designated receiver object.method syntax, though the
function call method(object) is still valid

	Object-REXX uses

		object~method

> send method to object   (Hypertalk, OpenXION)
> 
-- 
	Wulfraed                 Dennis Lee Bieber         AF6VN
        wlfraed@ix.netcom.com    HTTP://wlfraed.home.netcom.com/

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


#38726

FromMark Janssen <dreamingforward@gmail.com>
Date2013-02-11 21:12 -0800
Message-ID<mailman.1683.1360645965.2939.python-list@python.org>
In reply to#38469
On Fri, Feb 8, 2013 at 9:48 AM, Rick Johnson
<rantingrickjohnson@gmail.com> wrote:
> On Friday, February 8, 2013 9:16:42 AM UTC-6, Steven D'Aprano wrote:
>> Rick Johnson wrote:
> Just because /everything/ in Python is an object does not mean that Python is 100% OOP.

The whole idea of "make everything an object" is possibly a misguided
sense of puritanism anyway.   I wouldn't harp on that point to much.
But I really like your other developments.  Like the following

> If so, Python would have a supertype called "Collection" that wold define all methods that operate on collections. Some of these include:
>
>  len, any, all, length, isempty, __getitem__, __setitem__, etc...

I think this is a great idea and fixes a language wart which put
irrelevant methods into the builtin namespace.

> Then any collection subtype would inherit from this supertype and get the methods for free.

Yes.  OOP encapsulation.  But I question whether strings should be
considered collections.  This is a spurious usage issue, not something
in an integrated object model (see below on what I mean).

>> And a *really* smart language designer will have realised this ahead of
>> time, and designed the language to encourage the use of protocols like
>> this, instead of insisting on the slavish application of obj.method syntax.
> Using built-in functions to operate on objects is foolish because you are placing extra burden on the programmer to know which /functions/ work with which /types/. The *only* functions that should be global are the kind that will work on *ANY* object. But then again, the Object type could hold these methods!

Exactly.  This gets us closer to the real Python3000 that I've been
waiting for....

> len, all, and any (just to name a few) only work for collections types and as such should be methods of these types. The global functions:
>
>   sum, len, any, all, enumerate, map, max, min, reversed, sorted, zip
>
> can only be applied to sequence types, or subtypes of a sequence type. So using a /real/ OOP paridigm we would do the following:
>
> ## START TRUE OOP PARIDIGM ##
> [[snip]]

This is a great start, I think, but I think it's time to really
re-evaluate the whole data model again.  Before Python was trying to
"have everything", and have the flexibility to adapt for everyone, but
sometimes I think there's too much flexibility  and options and it
leads to sloppiness.  I would argue it's time for a refactor and
re-think the object model.

> class Object(SuperType):
>     def dir
>     def help
>     def id
>     def isinstance?(Type)
>     def issubclass?(Type)
>     def super
>     def type

I like the general line-of-thought, but some of these are
questionable.  I think it's essential to have help() outside any class
-- the built-in, global methods serve an important purpose of setting
the culture for a language, and help, (and my proposed test()) builtin
are part of (or would be) the community.

> class SequenceBase(Object):
>     def sum
>     def filter(proc)
>     def map
>     def max
>     def min
>     def reverse
>     def reduce(proc)

Here again, you see how the early python community put these in the
global namespace because of the bias that they had such (admittedly()
cool builtin collection types in the language.  But now, it's
interesting to reconsider these ideas.

> ## END TRUE OOP PARIDIGM ##
>
> You see, 100% OOP uses encapsulation, inheritance, sub-typing, etc, etc... But most fundamental to OOP is interface (methods belonging to objects), not global functions applied to objects in some haphazard fashion that some self-appointed dictator pull from his backside due to his fear of true OOP style!

That's not quite fair to the BDFL; you're criticizing the community
that made Python great.  That, of course, doesn't mean that it's still
logical to keep them out there in the global scope, exposed for all to
see.

> Python is not 100% OOP. Heck you cannot fairly apply a specific percentage level because Python's level of OOP is defined by each user of the language. The best way to describe Python is as promiscuous language who secretly longs to be 100% OOP, and to fulfill this fantasy it cross-dresses in OOP lingerie on the weekends.

That's a funny quote, besides its questionable accuracy, but your
initial sentences point out that having a unified data model might
actually be of use.  A unified data model does for data what lexical
definitions and parsers do for code:  organize it in a well-defined
way that is a *complete* specification for all possible data
organizations.  (But see my other posts about that.... ;^)

Mark
Tacoma, Wa

[toc] | [prev] | [standalone]


Page 3 of 3 — ← Prev page 1 2 [3]

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


csiph-web