Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Implicit conversion to boolean in if and while statements

Reply
Thread Tools

Implicit conversion to boolean in if and while statements

 
 
Rick Johnson
Guest
Posts: n/a
 
      02-10-2013
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 difficultfor 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.
 
Reply With Quote
 
 
 
 
Steven D'Aprano
Guest
Posts: n/a
 
      02-10-2013
Rick Johnson wrote:

> IMO "Set Types" should only exists as a concequence of "freezing" an
> array,


Sets are not frozen lists.

> and should have NO literal syntax avaiable.


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.

So, in Python 4000, my vote is for set literals { } to create frozensets,
and if you want a mutable set, you have to use the set() type directly.


--
Steven

 
Reply With Quote
 
 
 
 
Roy Smith
Guest
Posts: n/a
 
      02-10-2013
In article <5117868b$0$29998$c3e8da3$ om>,
Steven D'Aprano <steve+> wrote:

> Sets are not frozen lists.


Right. Tuples are frozen lists (ducking and running).
 
Reply With Quote
 
Thomas Rachel
Guest
Posts: n/a
 
      02-10-2013
Am 10.02.2013 12:37 schrieb Steven D'Aprano:

> So, in Python 4000, my vote is for set literals { } to create frozensets,
> and if you want a mutable set, you have to use the set() type directly.


4000 sounds about long future.

In the meanwhile, a new syntax element could be introduced fpr
frozensets, such as {{ }} or something. (Although that might clutter
with a set containing a set.)


Thomas
 
Reply With Quote
 
Rick Johnson
Guest
Posts: n/a
 
      02-11-2013
On Saturday, February 9, 2013 10:50:25 PM UTC-6, Chris Angelico wrote:
> [...]
> I don't understand. Wouldn't freezing an array (list) result in a
> tuple? And, why should there be no literal syntax for them?
>
> Having a convenient literal notation for every basic type is extremely
> handy.


Actually i must admit that you are correct. Of course the problem with literal syntax is symbol congestion. But i have a solution. A solution that cansurvive the limited number of grouping chars that python employs now. Except, i will define them explicitly

{}: denotes ANY mapping object.
[]: denotes ANY mutable sequence object.
(): denotes ANY immutable sequence object.
<>: Hmm, there must be a good use for this one!

The key to removing complexity is to declare the literal syntax much the way Python "represents" a "set". Observe:

py> set([1,2,3])
set([1,2,3])

Using this syntax we can apply "grouping" chars in proper context when writing literal syntax. The only problem is how do we make this syntax unique enough to avoid confusion and complexity??? Some hypothetical literal syntax, "syntaxes", include:

<set>[1,2,3] # Set literal
<set>(1,2,3) # FrozenSet literal

set=>[1,2,3] # Set literal
set=>(1,2,3) # FrozenSet literal

set::[1,2,3] # Set literal
set:1,2,3) # FrozenSet literal

set<[1,2,3]> # Set literal
set<(1,2,3)> # FrozenSet literal

<set[1,2,3]> # Set literal
<set(1,2,3)> # FrozenSet literal

set([1,2,3]) # Set literal
set((1,2,3)) # FrozenSet literal


....and to avoid conflicts with the "set" function, we just remove the set function! Only the types list, dict, and tuple(bka:StaticList!) should have a built-in constructor function, the remaining should have a typical OOP style constructor:

mySet = Set([1,2,3])
mySetLiteral = set([1,2,3])

 
Reply With Quote
 
Rick Johnson
Guest
Posts: n/a
 
      02-11-2013
On Saturday, February 9, 2013 10:50:25 PM UTC-6, Chris Angelico wrote:
> [...]
> I don't understand. Wouldn't freezing an array (list) result in a
> tuple? And, why should there be no literal syntax for them?
>
> Having a convenient literal notation for every basic type is extremely
> handy.


Actually i must admit that you are correct. Of course the problem with literal syntax is symbol congestion. But i have a solution. A solution that cansurvive the limited number of grouping chars that python employs now. Except, i will define them explicitly

{}: denotes ANY mapping object.
[]: denotes ANY mutable sequence object.
(): denotes ANY immutable sequence object.
<>: Hmm, there must be a good use for this one!

The key to removing complexity is to declare the literal syntax much the way Python "represents" a "set". Observe:

py> set([1,2,3])
set([1,2,3])

Using this syntax we can apply "grouping" chars in proper context when writing literal syntax. The only problem is how do we make this syntax unique enough to avoid confusion and complexity??? Some hypothetical literal syntax, "syntaxes", include:

<set>[1,2,3] # Set literal
<set>(1,2,3) # FrozenSet literal

set=>[1,2,3] # Set literal
set=>(1,2,3) # FrozenSet literal

set::[1,2,3] # Set literal
set:1,2,3) # FrozenSet literal

set<[1,2,3]> # Set literal
set<(1,2,3)> # FrozenSet literal

<set[1,2,3]> # Set literal
<set(1,2,3)> # FrozenSet literal

set([1,2,3]) # Set literal
set((1,2,3)) # FrozenSet literal


....and to avoid conflicts with the "set" function, we just remove the set function! Only the types list, dict, and tuple(bka:StaticList!) should have a built-in constructor function, the remaining should have a typical OOP style constructor:

mySet = Set([1,2,3])
mySetLiteral = set([1,2,3])

 
Reply With Quote
 
alex23
Guest
Posts: n/a
 
      02-11-2013
On Feb 8, 4:29*pm, Rick Johnson <rantingrickjohn...@gmail.com> wrote:
> That's a strange thing to say when you go on to provide an example that tests the validity of the object "each and every time":


Here's a tip: context is important. I was referring to not having to
*explicitly* test if a label *is defined* in order to be able to use
it, which is something you need to do in other languages, such as
Javascript:

var func = function() { throw EventException; }
a = func()
if ( a == '1') ... // this raises a ReferenceError as 'a' is not
defined
if ( typeof a !== 'undefined' && a == '1')... // this guards
against the ReferenceError

> And i find it to be incredibly asinine.


I find your smugness to be much the same.

> Consider this:
> * * if connect("my:db") as db:
> * * * * <do something>
>
> No need to make a call and then test for the validity of the call when you can do both simultaneously AND intuitively.


No need to learn a language when you can just make crap up and whine
when it doesn't work.

> *school-bell-rings*


You're "schooling" others using a hypothetical variant of an existing
language which you believe should conform to your a priori assumptions
about how such a language should work? You're "schooling" people who
_read the documentation_ when you admit to not doing so yourself?

You're not asinine, you're just an asshole.

 
Reply With Quote
 
Rick Johnson
Guest
Posts: n/a
 
      02-11-2013
On Sunday, February 10, 2013 5:37:46 AM UTC-6, Steven D'Aprano wrote:
> Rick Johnson wrote:
> > IMO "Set Types" should only exists as a concequence of "freezing" an
> > array,

>
> Sets are not frozen lists.


Indeed. That wording was a bit clumsy on my part.

> > and should have NO literal syntax available.


I may have spoken too soon on this issue. My reasoning for /not/ having a literal set syntax was due to symbol congestion, however as i described in another post, the problem can be solved by literally "type declaring" the literal.

 
Reply With Quote
 
Rick Johnson
Guest
Posts: n/a
 
      02-11-2013
On Saturday, February 9, 2013 11:04:42 PM UTC-6, Chris Angelico wrote:
> On Sun, Feb 10, 2013 at 3:54 PM, Rick Johnson wrote:
> > Well Chris i have wonderful news for you! Python /does/
> > have "homogenous arrays", and they're called, wait for
> > it......... arrays!


> That's not a built-in. But you were the one who complained about the
> way sum() could be applied to a list that contains a non-integer;
> maybe your solution is simply to ignore sum() and work with
> array.array?


Yes i could, however by doing so i would be ignoring the inconsistent elephant in the room. My crusade is to bring consistency and logic to languages,and if i have any free time afterwards, to remove multiplicity. There are two types of people in the world Chris, those that lead and those that follow.

> Nice how you can complain about Python for not having something, then
> heap scorn on me for not being aware that it's there in the stdlib.
> (Which, by the way, I freely admit to being less than fully familiar
> with. Even less familiar with what's on PyPI.)


Well i would expect anyone who considers himself a python programmer (not to mention "pythonista"!) to at minimum be familiar with the stdlib. That does not mean he must have attained black belt level kung-fu in /every/ stdlib module, but he must at least /know/ all the modules names and all types that Python offers. Is that really too much to ask Chris?
 
Reply With Quote
 
Rick Johnson
Guest
Posts: n/a
 
      02-11-2013
On Saturday, February 9, 2013 11:04:42 PM UTC-6, Chris Angelico wrote:
> On Sun, Feb 10, 2013 at 3:54 PM, Rick Johnson wrote:
> > Well Chris i have wonderful news for you! Python /does/
> > have "homogenous arrays", and they're called, wait for
> > it......... arrays!


> That's not a built-in. But you were the one who complained about the
> way sum() could be applied to a list that contains a non-integer;
> maybe your solution is simply to ignore sum() and work with
> array.array?


Yes i could, however by doing so i would be ignoring the inconsistent elephant in the room. My crusade is to bring consistency and logic to languages,and if i have any free time afterwards, to remove multiplicity. There are two types of people in the world Chris, those that lead and those that follow.

> Nice how you can complain about Python for not having something, then
> heap scorn on me for not being aware that it's there in the stdlib.
> (Which, by the way, I freely admit to being less than fully familiar
> with. Even less familiar with what's on PyPI.)


Well i would expect anyone who considers himself a python programmer (not to mention "pythonista"!) to at minimum be familiar with the stdlib. That does not mean he must have attained black belt level kung-fu in /every/ stdlib module, but he must at least /know/ all the modules names and all types that Python offers. Is that really too much to ask Chris?
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Re: Implicit conversion to boolean in if and while statements Stefan Behnel Python 0 07-15-2012 09:17 AM
Re: Implicit conversion to boolean in if and while statements Chris Angelico Python 0 07-15-2012 08:47 AM
Subtle difference between boolean value and boolean comparison? Metre Meter Javascript 7 08-06-2010 08:40 PM
if statements and case statements questions John Crichton Ruby 6 07-12-2010 06:17 PM
difference between 'boolean' and 'java.lang.Boolean' J Leonard Java 4 01-19-2008 02:56 AM



Advertisments