Re: Implicit conversion to boolean in if and while statements
On Jul 15, 4:53 pm, Chris Angelico wrote: > Then the construct "if bool(some_condition):" is redundant. Wrong again, pay attention Chris! It's ONLY redundant IF "some_condition" is a rich comparison: like "(a==b)" OR a boolean function: like "callable(a)". If HOWEVER we want to "truth test" an object (as in: "if obj") we should be FORCED to use the bool! Why? Because explicit is better than implicit and readability counts if we want to create maintainable code bases! if bool(obj) and a==b: # Correct! if obj and a==b: # Incorrect! Both lines of code currently produce the same result because "somebody" decided to give objects esoteric boolean values. Sure, we saved a few key stokes in a condition, but sadly at the cost of readability and consistency. I see no reason why choosing implicit resolution is better than explicit resolution. Saving six keystrokes is simply not enough! Python's motto has always been "readability counts", and for that reason, we should return to Explicit Boolean Resolution if we want to adhere to those principals. -- http://mail.python.org/mailman/listinfo/python-list
Re: Implicit conversion to boolean in if and while statements
On Jul 15, 8:51 pm, Chris Angelico wrote: > On Mon, Jul 16, 2012 at 11:21 AM, Ranting Rick > > wrote: > > If HOWEVER we want to "truth test" an object (as in: "if obj") we > > should be FORCED to use the bool! Why? Because explicit is better than > > implicit and readability counts if we want to create maintainable code > > bases! > > > if bool(obj) and a==b: # Correct! > > if obj and a==b: # Incorrect! > > That still doesn't answer the question of what bool(obj) should do if > obj is not a bool, and why if can't do the exact same thing, since if, > by definition, is looking for a boolean state selector. > > ChrisA My point is no different than this example: py> cost = 1.75 py> cost 1.75 py> 'Cost = ' + cost Traceback (most recent call last): File "", line 1, in 'Cost = ' + cost TypeError: cannot concatenate 'str' and 'float' objects py> 'Cost = ' + str(cost) 'Cost = 1.75' We DON'T want Python to silently convert "cost" to a string. What we DO want is to force the author to use the str function thereby making the conversion explicit. Same with converting objects to bools. We DON'T want "if" to magically convert a non-boolean into a boolean. What we DO want is to force the author to use the bool function thereby making the conversion explicit. By doing so we transform confusion into comprehension. By doing so we maintain the principals of readability counts. -- http://mail.python.org/mailman/listinfo/python-list
Re: Implicit conversion to boolean in if and while statements
On Jul 15, 9:13 pm, Steven D'Aprano wrote:
> I have just written a bunch of code with about two dozen examples similar
> to this:
>
> for item in (seq or []):
> do_something_with(item)
>
> iterates over seq if it is non-empty, or the empty list. Writing it like
> this would be more painful, more complex, less readable and less
> idiomatic:
>
> if seq is not None:
> for item in seq:
> do_something_with(item)
>
> not to mention completely unnecessary if you have already checked that
> seq is either None or a sequence, and not some other arbitrary value.
Short circuitry is a powerful tool! But why the heck would your
sequences ever be None? Are you using None as a default? And if so,
why not use an empty sequence instead ([], {}, "")?
--
http://mail.python.org/mailman/listinfo/python-list
Re: Implicit conversion to boolean in if and while statements
On Jul 15, 9:15 pm, Devin Jeanpierre wrote: > For example, instead of "if stack:" or "if bool(stack):", we could use > "if stack.isempty():". This line tells us explicitly that stack is a > container. Or instead of "if dist:" or "if bool(dist):" we could use > "if dist == 0:". This tells us explicitly that stack is a number. > Supposedly this makes it easier to read code. It certainly reads more > like English! :) Yes, but this approach involves adding new "value testing" methods to every object. Whilst these specific methods would probably inject more comprehension than using bool, i believe the bool function can handle this problem better due to its monolithic and generic nature. No need to memorize which method is needed for strings, or integers, or lists, etc... just use bool and everything works. As for the semantics, we should let the object decide how to respond to a __bool__() request. But what's the point of having a bool function if we refuse to use it correctly? We force str, int, and float conversion all day, but not the bool? Where is the consistency? Where is the bool!? -- http://mail.python.org/mailman/listinfo/python-list
Re: Implicit conversion to boolean in if and while statements
On Jul 15, 9:58 pm, Steven D'Aprano wrote: > On Sun, 15 Jul 2012 18:21:06 -0700, Ranting Rick wrote: > > If HOWEVER we want to "truth test" an object (as in: "if obj") we should > > be FORCED to use the bool! Why? Because explicit is better than implicit > > And this is why Rick always writes code like: ... Traceback (most recent quip last): Author: "", line 7, in LogicalFallacyError: "Reductio ad absurdum" -- http://mail.python.org/mailman/listinfo/python-list
Re: Implicit conversion to boolean in if and while statements
On Jul 15, 11:03 pm, Steven D'Aprano wrote:
> On Sun, 15 Jul 2012 22:15:13 -0400, Devin Jeanpierre wrote:
> It boggles my mind that people who are perfectly happy to program to an
> interface or protocol when it comes to (say) iterables, numbers or even
> big complex classes with dozens of methods, suddenly freak out at the
> thought that you can say "if obj" and obj is duck-typed.
"if obj" is in essence doing "if bool(obj)" behind the scenes. My
question is: Why hide such valuable information from the reader? It's
obvious that "if bool(obj)" will return a boolean; whereas "if obj" is
ambiguous.
> There's a distinct lack of concrete, actual problems from duck-typing
> bools, and a heavy over-abundance of strongly-held opinion that such a
> thing is self-evidently wrong.
If the multitudes of misunderstandings from "if obj" on this list have
not convinced you yet, then i lack the energy to educate you!
> > As far as I know, the only use of having a polymorphic boolean
> > conversion is reducing the amount of typing we do.
>
> The same could be said about *every* polymorphic function.
For which "bool" IS!
Wikipedia to the rescue:
"""In computer science, polymorphism is a programming language feature
that allows values of different data types to be handled using a
uniform interface. The concept of parametric polymorphism applies to
both data types and functions. A function that can evaluate to or be
applied to values of different types is known as a polymorphic
function."""
bool("a") -> True
bool(0) -> False
bool([1,2,3]) -> True
bool(True) -> True
> The benefit is not just because you don't wear out your keyboard as fast.
> The benefit is the same for all other polymorphic code: it lets you write
> better code faster with fewer bugs and less need for unnecessary type
> restrictions.
There are NO type restrictions for bool.
> If there are a few corner cases where you actually *need* to restrict the
> type of your flags to a actual bool, well, Python gives you the tools to
> do so.
Yes, the bool()
--
http://mail.python.org/mailman/listinfo/python-list
Re: Implicit conversion to boolean in if and while statements
On Jul 15, 11:20 pm, Steven D'Aprano wrote: > (It's not like explicit and implicit are distinct -- everything depends > on something implicit, if only the meaning of the words you use to > describe it.) > > It certainly doesn't mean that the semantics of Python the language must > be written out explicitly every time you use each feature. Of course not. Don't be ridiculous. > for x in sequence: [...] This syntax is explicit *enough*. We don't need to be any more explicit. But if you are going to argue that "if obj" is *explicit enough*, then apply your argument consistently to "String"+1.75 also. Why must we be explicit about string conversion BUT not boolean conversion? Can you reduce this to the absurd? Or will you just choose to ignore this valid point? -- http://mail.python.org/mailman/listinfo/python-list
Re: [Newbie] Require help migrating from Perl to Python 2.7 (namespaces)
On Dec 24, 9:48 am, Dave Angel wrote: > Pep8 recommends a particular style within a function name, separating > 'words of a name by underscore. I happen to loathe that style, so I'm > clearly not the one who would critique someone for not following the > guideline. I say getFile(), the pep says get_file(). Slightly off topic, but still quite relevant: I happen to like that style for public methods (even though Python has no real public/ private methods). class Foo(): def __init__(self) def __secretMethod() # Secret handshake required! def _privateMethodOrAccessor() # Self only. def sharedMethod() # Self and/or descendants only. def public_method() # Total whore. -- http://mail.python.org/mailman/listinfo/python-list
Re: [Newbie] Require help migrating from Perl to Python 2.7 (namespaces)
On Dec 26, 11:02 pm, Steven D'Aprano wrote: > On Wed, 26 Dec 2012 20:07:53 -0800, Rick Johnson wrote: > > My specific point is that the English word "variable" is unambiguous > > I'm sorry, do you mean "variable" the noun, or "variable" the adjective? > [snip: sliding down the rabbit hole of a polysemantic nightmare...] And now my dear friend you arrive at the horrible truth. The truth that your language is defeating you. The truth that you dare not speak because of the fear of unfamiliarity. You don't like that feeling, you fear it, you prefer the warmth of clinging to a warm fuzzy something, EVEN IF that something is a abomination. So what do we do? Well the obvious answer is to scrap the whole thing and start over. Start with a system of word creation that is intelligently expandable instead of what we have now which is a haphazard at best. Stringing bits of Greek with bits of Latin may increase your social status at the local chess club, but you are only injecting more garbage into the system. The whole architecture is flawed. It's flawed in greek, it's flawed in latin, and it's flawed in Python. You cannot create gold from lead: "Polish a turd, it's still a turd!" But short of re-inventing the English language ( heck, you people won't even _admit_ to the inconsistencies in Python syntax, much less commit to _repairing_ them!) the flaws in natural language cannot be used as an excuse to inject illogic/inconsistency/multiplicity at your whim. We should hold ourselves to a higher standard. Every keyword, syntactical structure, style, etc, etc, should be based on logical foundations; not adolescent fads or propagating more idiotic cultural traditions. You piss and moan about language X and how asinine the language is, them you go and repeat the same stupid mistakes simply because you don't want to "rock the boat"?! """Well, urm, i don't particularly like "aspect x" about this language, but most programmers have internalized the practice and i don't want to confuse them with intelligent design, consistency or logic, so i'll just propagate more of this stupidity so everyone can feel warm and fuzzy.""" Well thanks Mr. language designer, now we'll be corralling braces for another fifty FREAKING YEARS! PS: Grow a pair! -- http://mail.python.org/mailman/listinfo/python-list
Re: Python GUI questions
On Mar 19, 8:25 pm, maiden129 wrote:
> Here is my try to answer some of questions:
>
> [snip code]
I don't understand why you are wrapping this code into a class. Are
you trying to create something reuseable?
> I'm just struggling with only how to create an object that
> will hold a single character that the user will enter.
I would suggest that you scrape this code and start over, and a good
starting point would be at the BEGINNING.
All (well, *most*) GUI applications begin with a "root window". Once
you have created the main window you can start placing widgets inside
the window. This is the basic outline of a Tkinter GUI application.
1. Create the root window.
2. Create all the needed sub-widgets and arrange them properly.
3. Start processing user events.
So using the code you provided (and rearranging it to make sense) you
would end up with this:
## START CODE ##(Python 3.x)
import tkinter as tk
from tkinter.constants import LEFT
def cbButton(self):
print('I should do something here!')
root = tk.Tk()
root.title("Window")
w=tk.Label(root, text="Enter a string")
w.pack(side=LEFT)
e1 = tk.Entry(root, bd=5)
e1.pack(side=LEFT)
b=tk.Button(root, text="Count", command=cbButton)
b.pack(padx=5, pady=5)
root.mainloop()
## END CODE ##
Notice that i used a more intelligent form of import that will
maintain a clean namespace. Tkinter is a very BLOATED module, and
since you are just learning you won't be aware of the names that could
cause problems.
Also notice that my style is consistent. Not following an accepted
coding style is condemnable, however, being inconsistent with your
style is abominable!
PS: Also, trim those excessive quotes please.
--
http://mail.python.org/mailman/listinfo/python-list
