osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Tutor] beginning to code


>
> >
> > I would agree that testing any of those for '== True' or
> > the like is pointless redundancy,
>
> But what's wrong with syntactical redundancy when it brings
> _clarity_ to the source code? And why can't Python be smart?
> Consider the collowing code:
>
>     if bool(someObject) == True:
>         # Do something
>
> Yes, from a "byte-code perspective", this source code is
> superfluous, but, from a source code perspective, this code
> is perfectly balanced between explicit and implicit.


I can't agree with you.  It's too redundant.  It doesn't provide any
information
about what coder think.

While PEP 8 recommends `if x:`, I accept `if x > 0` or `if len(x) > 0` when
I review
code in my company.  While it is redundant in most case, it express what
writer thinking.
But I never permit `if bool(x) == True`.  It only express `if x is truthy
value`in complicated way.  `if x` is best way to express `if x is truthy
value`.



> So what
> should Python do when such intuitive, but not so much
> efficient, code is encountered? Easy! Python should optimize
> it! Observe:
>
>     FROM: "if bool(someObject) == True:"
>       TO: "if someObject:"
>
>     FROM: "if bool(someObject) == False:"
>       TO: "if not someObject:"
>
> Why is "source code optimization" such a difficult concept
> for some people in this community to grasp? In this case,
> Python doesn't even need to know anything about these
> objects, no, the solution is just a simple matter of string
> substitution.
>
>
While such type of optimization is possible, it's not easy as you think.
You can overwrite `bool`.

def bool(x):
    return !x

if 0:
    print("not shown")

if bool(0) == True:
    print("shown")


But my point is only readability.  I don't agree `if bool(x) == True:` is
clear
than `if x:`.

Regards,
-- 
Inada Naoki <songofacandy at gmail.com>