Re: Is vars() the most useless Python built-in ever?

2015-12-14 Thread Rick Johnson
On Friday, December 11, 2015 at 10:45:02 PM UTC-6, Steven D'Aprano wrote:
> On Sat, 12 Dec 2015 09:13 am, Rick Johnson wrote:
>
> > Intuitiveness and productivity have a
> > synergy like peas and carrots! One cannot be productive if one is fighting
> > an unintuitive interface. Could you drive with your toes? How about your
> > tongue?
>
> Drive a car with my tongue? Perhaps not, but I could drive a car with my
> mouth if it were equipped with a sufficiently powerful interface.
>
> "Driver, please take me to the airport."

Sorry Steven, but that command will not be executed. First
you must say: "Ok Google". ;-)

Even google is not insane enough to write software that
attempts interpretation of every spoken within ear-shot of
it. But your interface has an even greater problem: since
software cannot yet read minds, and since most metropolitan
areas contain more than one airport, you may want to be more
specific than "take me to the airport". Heck, why not follow
that one with "take me shopping". ;-)

Not only have you demonstrated that your "mock interface" is
un-intuitive, your commands are so implicit that the banter
between human<->software is likely to descend into a sad
parody of Abbott and Costello!

> > Sure, even the most atrocious interface can be "learned", but what i
> > cannot understand, except in the case of you being a contrarian, is why
> > you would argue *AGAINST* intuitive interfaces? And believe it or not,
> > *SYNTAX* is an interface! As are paradigms!
>
> I do believe that you are arguing against a strawman. I don't think that
> anyone here has argued *against* "intuitiveness", all else being equal. But
> you are glossing over a whole lot of real complexity:
>
> - what makes you think all else actually is equal?
>
> - who decides what is intuitive and what isn't? why should we take
>   your word over what's intuitive and what isn't?
>
> - intuitive for who? my dad, who has never used a computer? my mum,
>   who has used a computer but only for word processing and web
>   browsing? a ten year old maths prodigy? a thirty year veteran
>   of C programming? a beginner to programming with a month's
>   experience in PHP?
>
> - what level of power are we willing to forgo in order to keep
>   the language "intuitive"?
>
> - what the hell does "intuitive" mean anyway?

Who's needs Abbott! Listen Steven, the litmus test for
intuitiveness is simple: if the overwhelming majority of the
users find it to be intuitive during the learning process,
then your interface is intuitive. That's it.

> I know what the definition of the word is, but it doesn't apply to
> programming language interfaces. As has been pointed out many times, the
> only truly intuitive interface is the nipple. Everything else has to be
> learned.

And what experience do *YOU* have with breast feeding that
would in any way qualify *YOU* to make such an assertion?

> In practice, "intuitive interface" gets bandied about in two ways:
>
> (1) Some people use it as a thought-terminating cliche. What they really
> mean is that they want this interface feature, for reasons of their own,
> and by calling it 'intuitive', they hope to bamboozle or intimidate others
> into backing down and accepting the feature. Who could possibly be
> against "intuitive" interfaces? That's like being against "usefulness",
> or "flexibility".
>
> When people start protesting about others being "against intuitive
> interfaces" (especially if they SHOUT the word "against", that's an good
> sign that they're using it as a thought-terminating cliche. To these
> people, "intuitive" is like "New And Improved!!!" to advertisers.
>
> (2) Others use it to mean an interface which is:
>
> * predictable;
> * consistent;
> * easy to explore and learn;
> * and "easy to use" in some vague sense.

This last comparison looks an awful lot like a straw-man
Steven. Nice. Extra points for painting me as a bully, and
then using my exact definition of intuitiveness but applying
it to the "friendly challenger". Your sleight of hand is
impressive my friend.

> [...]
>
> And most importantly, they recognize that programmers are beginners for
> perhaps 1% of their programming life: you might be completely new to
> programming for three months out of a 30 year span of programming. Why
> optimize the language for something that you will use for less than 1% of
> your productive lifespan? Apart from intentional beginner's languages like
> Scratch, for most languages it makes sense to add power even if it
> increases the learning curve.

I can assure you that complexity is not sacrificed when we
design interfaces to be intuitive. And to illustrate, we
need look no further than the automobile for a fine example.
The interface for driving a car is not only intuitive, it is
consistent!

  It is intuitive because it exposes a small number of high
  level operator components: the steering wheel, the brake
  petal, and the accelerator petal.

  And it is consistent because no matter what brand 

Re: Is vars() the most useless Python built-in ever?

2015-12-11 Thread Chris Angelico
On Sat, Dec 12, 2015 at 3:44 PM, Steven D'Aprano  wrote:
> On Sat, 12 Dec 2015 09:13 am, Rick Johnson wrote:
>
>> Intuitiveness and productivity have a
>> synergy like peas and carrots! One cannot be productive if one is fighting
>> an unintuitive interface. Could you drive with your toes? How about your
>> tongue?
>
> Drive a car with my tongue? Perhaps not, but I could drive a car with my
> mouth if it were equipped with a sufficiently powerful interface.
>
> "Driver, please take me to the airport."

Bring on the self-driving cars! They're already comparable to human
drivers in skill. Instead of getting my sister to chauffeur me around,
I could just hop in my automatic car, tell it my destination, and sit
back with my laptop. All I need is for them to become more affordable.

> In practice, "intuitive interface" gets bandied about in two ways:
>
> (2) Others use it to mean an interface which is:
>
> * predictable;
> * consistent;
> * easy to explore and learn;
> * and "easy to use" in some vague sense.
>
>
> They recognise that what seems unpredictable to one person may be perfectly
> predictable to a more experienced user.

Which really means that "intuitive" is a feature of
skill/comprehension transference. This is the exact reason for the
extensive use of metaphors in design - even though those metaphors
often get orphanned, they are useful. How many people have actually
carried around a folder full of documents? A few of you, maybe? How
many of you instantly understand what a folder is, and that you can
drag documents into it? Everyone. It makes perfect sense that you
should be able to put stuff inside other stuff, so we can extend that
to "compressed folders" or "shared folders" or "backed-up folders" or
any other adjective you care to use. These are then touted as
"intuitive" - eg I can use Dropbox by just sticking something into the
Dropbox folder, ergo this interface is intuitive.

Most modern languages seem to assume at least some knowledge of
mathematics (maybe as far as algebra). It's considered intuitive that
(1.0 + 2.0 / 6.0) should be equal to 1.333, because the fraction bar
translates fairly readily into the slash. (And it doesn't equal 0.5,
because the order of operations demands it.) Learning that you need
the asterisk for multiplication is usually not a problem - at worst,
it's the price you pay for multi-letter names (xy is distinct from
x*y). Give people a staircase of small comprehensions and they'll
master it; shove them up against a wall of new knowledge and they
can't mantle up.

>> (1) When laymen consider the word "print" (in the context of computing),
>> they first think of "sending a document to a printing device".
>
> No they don't. They think of printing to the screen, not printing to paper.
>
> Even if they think of printing to paper, it takes them less than a second to
> learn otherwise. That's a fantastic user interface: you can learn and
> explore the functionality of the language very easily.

Maybe if you had people entering code on a typewriter and seeing the
output two hours later on parchment, then they'd assume it meant print
to paper. Does anyone these days even print out listings?

There are two broad types of code: Simple and complex. There are two
broad types of job: Common and unusual. If you see a very simple piece
of code, you will generally expect that it's doing something common.
Let's posit a domain-specific language for building objects for a
MMORPG. Here's a piece of code, with all crucial keywords replaced
with names from my current D&D campaign:

soyutlanma on_wield(player)
[[[
   parildiyor player#level >> 72
   [[[
  dogmakta «You cannot wield this weapon.»
  uzakta
   ]]]
   parildiyor player#classes << {«bard»}
   [[[
  dogmakta «You can ne'er wield this weapon.»
  uzakta
   ]]]
   dogmakta «It feels strong and sturdy in your hand.»
   taneleri item, inventory
   [[[
  parildiyor kaylee<->item
  [[[
  dogmakta «Your helmet glows brightly with increased magic!»
  ]]]
   ]]]
]]]

So, what operations do you think would be sufficiently common to
justify language keywords? I've deliberately made them nonsense so
there's no clues from the words themselves, but I expect that anyone
here should have a reasonable shot at figuring out what things might
mean. Voila! I've made an intuitive language. Right?

Sending content to a printer is at least as complicated as writing to
a file on disk. I would expect that any language keyword or built-in
function for generating paper output should, at a minimum, stipulate
which printer it's going to, and have a means of saying "I'm done with
that page now". We don't tend tto "log to prn" these days, so you
wouldn't expect to see a command/function to "write this line to the
printer, and if there are 66 lines written, push that page out and
bring the next one in".

> (One of the weaknesses of Python, and nearly all mainstream programming
> languages, is that there is nothing even remot

Re: Is vars() the most useless Python built-in ever?

2015-12-11 Thread Steven D'Aprano
On Sat, 12 Dec 2015 09:13 am, Rick Johnson wrote:

> Intuitiveness and productivity have a
> synergy like peas and carrots! One cannot be productive if one is fighting
> an unintuitive interface. Could you drive with your toes? How about your
> tongue?

Drive a car with my tongue? Perhaps not, but I could drive a car with my
mouth if it were equipped with a sufficiently powerful interface.

"Driver, please take me to the airport."


> Sure, even the most atrocious interface can be "learned", but what i
> cannot understand, except in the case of you being a contrarian, is why
> you would argue *AGAINST* intuitive interfaces? And believe it or not,
> *SYNTAX* is an interface! As are paradigms!

I do believe that you are arguing against a strawman. I don't think that
anyone here has argued *against* "intuitiveness", all else being equal. But
you are glossing over a whole lot of real complexity:

- what makes you think all else actually is equal?

- who decides what is intuitive and what isn't? why should we take 
  your word over what's intuitive and what isn't?

- intuitive for who? my dad, who has never used a computer? my mum, 
  who has used a computer but only for word processing and web 
  browsing? a ten year old maths prodigy? a thirty year veteran 
  of C programming? a beginner to programming with a month's 
  experience in PHP?

- what level of power are we willing to forgo in order to keep 
  the language "intuitive"?

- what the hell does "intuitive" mean anyway?

I know what the definition of the word is, but it doesn't apply to
programming language interfaces. As has been pointed out many times, the
only truly intuitive interface is the nipple. Everything else has to be
learned.

In practice, "intuitive interface" gets bandied about in two ways:

(1) Some people use it as a thought-terminating cliché. What they really
mean is that they want this interface feature, for reasons of their own,
and by calling it 'intuitive', they hope to bamboozle or intimidate others
into backing down and accepting the feature. Who could possibly be
against "intuitive" interfaces? That's like being against "usefulness",
or "flexibility".

When people start protesting about others being "against intuitive
interfaces" (especially if they SHOUT the word "against", that's an good
sign that they're using it as a thought-terminating cliché. To these
people, "intuitive" is like "New And Improved!!!" to advertisers.

(2) Others use it to mean an interface which is:

* predictable;
* consistent;
* easy to explore and learn;
* and "easy to use" in some vague sense.


They recognise that what seems unpredictable to one person may be perfectly
predictable to a more experienced user.

They recognise that consistency is partly a function of the user's own
understanding, not just they language alone. Even if the language is
designed with a single, consistent model (e.g. "everything is an object"),
if the user's mental model is wrong, they will fail to recognise the
consistency, or look for it in the wrong places.

And most importantly, they recognise that programmers are beginners for
perhaps 1% of their programming life: you might be completely new to
programming for three months out of a 30 year span of programming. Why
optimize the language for something that you will use for less than 1% of
your productive lifespan? Apart from intentional beginner's languages like
Scratch, for most languages it makes sense to add power even if it
increases the learning curve.

https://scratch.mit.edu/about/


[...]
> THE PRINT FUNCTION HAS TWO MAJOR ISSUES IN THE CONTEXT OF INTUITIVENESS:
> 
> (1) When laymen consider the word "print" (in the context of computing),
> they first think of "sending a document to a printing device". 

No they don't. They think of printing to the screen, not printing to paper.

Even if they think of printing to paper, it takes them less than a second to
learn otherwise. That's a fantastic user interface: you can learn and
explore the functionality of the language very easily.

(One of the weaknesses of Python, and nearly all mainstream programming
languages, is that there is nothing even remotely like an easy-to-explore
UI for programming GUI applications.)


> (2) The path to the underlying process is not even remotely clear. LIKE IT
> NOT, PRINT IS "MAGIC SYNTAX".

print does what it says of the tin: it prints (to the screen). You don't
have to understand how it manages that to use it effectively, just as you
don't have to understand calculus in order to use math.sqrt().



-- 
Steven

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is vars() the most useless Python built-in ever?

2015-12-11 Thread Rick Johnson
On Tuesday, December 1, 2015 at 10:49:19 PM UTC-6, Ian wrote:
> > It's a well know fact that GvR was inspired to create
> > Python from his experiences working with a language
> > called ABC -- and ABC was designed *EXCLUSIVELY* to be a
> > beginners language.
> Which is exactly what made ABC itself unsuitable for Guido's purpose, which
> was to create an *applications* language with better productivity than C to
> support users of Amoeba, the OS that he was working on at the time.

The key word here is "productivity". Intuitiveness and productivity have a 
synergy like peas and carrots! One cannot be productive if one is fighting an 
unintuitive interface. Could you drive with your toes? How about your tongue? 

Sure, even the most atrocious interface can be "learned", but what i cannot 
understand, except in the case of you being a contrarian, is why you would 
argue *AGAINST* intuitive interfaces? And believe it or not, *SYNTAX* is an 
interface! As are paradigms! 

> > Even a noob can intuit what is going on here. First we
> > have an *OBJECT* named "stdout, and we can extrapolate
> > that stdout is an abbreviation for StandardOutput. Next,
> > we see a method called "write", and, if our IQ is above
> > room temperature, then we can extrapolate what that
> > method will do.
> 
> This is absurd. You postulate a beginner so rank that they can't understand
> what "print" means, yet you expect them to intuitively know:
> 
> 1) what an object is;
> 
> 2) what a method is;
> 
> 3) that a method is identified by placing a period between the object and
> the name of the method;
> 
> 4) what "output" is in the context of programming;
> 
> 5) and not be confused about what makes the output "standard".

You accuse me of Reductio Ad Adsurdium, yet you commit the same offense, and 
then put words in my mouth?

Of course i don't expect a "rank noob" to understand these concepts 
*immediately*, however, the learning curve will be greatly reduced, and the 
depth of knowledge greatly expanded, when a clear path of consistent 
intuitiveness is baked-into the learning process -- it's all about breadcrumbs 
my dear boy, breadcrumbs!

THE PRINT FUNCTION HAS TWO MAJOR ISSUES IN THE CONTEXT OF INTUITIVENESS:

(1) When laymen consider the word "print" (in the context of computing), they 
first think of "sending a document to a printing device". LIKE IT NOT, "PRINT" 
IS A CONCEPTUAL CHAMELEON! It does the worst thing it can do, it distracts! 

(2) The path to the underlying process is not even remotely clear. LIKE IT NOT, 
PRINT IS "MAGIC SYNTAX". 

Of course the noob is not going to immediately intuit every atomic component of 
`stdout.write("blah")`, however, the road signs are there, and all he need to 
do is follow them. In fact, by learning from my example, not only will the noob 
learn the "magic" that exists under the hood, he will also learn a vital lesson 
(while dissecting the components) about the power of "divide and conquer". 

If we were to create a thought exercise that juxtaposes your argument with 
mine, we would find a great example in the "search for hidden treasure". You 
expect the noob to go into a dessert without a map and dig holes until he 
locates the treasure or dies of exhaustion. Whereas i will not only give the 
noob a map, i will draw a clear path on the map to the destination -- all he 
need to do is navigate! I don't know what's more absurd: your argument, or your 
ego?

> You're describing this as if your hypothetical beginner were learning
> Python in a vacuum. In reality, people learn from a teacher, or a book, or
> at minimum a tutorial.

Hmm. I'll bet you create teeny tiny variable names and then write a paragraph 
to describe them. Does the concept of "Self Documentation" mean anything to 
you? And, when correctly designed, the only tutorial that is needed is the the 
syntax! Heck, we are not writing assembly code here man, we're writing Python 
code for Guido's sake!

> Here's how you teach somebody what "print" does: instruct them to type
> print("hello world") at the interactive prompt. Note that Python writes
> "hello world" as a result. If they really want, they can check their
> printer and see that nothing came out. That's it. The student now
> understands what "print" means.

Yes, the timeless method of "trial and error" is expected if you're a trail 
blazer and there exists no previous knowledge, however, when this sort of 
teaching paradigm is used in areas where the processes have been previously 
dissected, it reflects a sadistic nature within the teacher. I'm of the opinion 
that learning "old tech" should be as intuitive as possible, and that, as 
knowledge spreads, we all prosper. However, you seem to adopt the teaching 
methods of a drunken and disorderly college sorority house captain. Students 
are not pledges to be tortured. They are our the future. And when we undermine 
them, we undermine our ourselves. 

 PUT THAT IN YOUR INTERPRETER AND RUN IT!
-- 
https://mail.pyth

Re: Is vars() the most useless Python built-in ever?

2015-12-11 Thread Rick Johnson
On Tuesday, December 1, 2015 at 1:34:54 AM UTC-6, Marko Rauhamaa wrote:
> Rick Johnson :
> 
> > python was originally created to be an easy language for noobs to
> > learn
> 
> Really? That's would be a silly objective for a programming language.
> 
> > many a noob has been stumped
> 
> So?
> 
> You have to first placate the experts and the "noobs" will follow.

Okay i get it. So in your opinion, a technology is *ONLY* worthy if it requires 
a large amount of special training to wield it? 

Well, in that case you'd better start organizing a revived Luddite movement, 
because i can assure you that as we progress into the future, more and more of 
the processes that required "human specialist" will be replaced with 
computational devices that are purposefully designed to expose the most 
intuitive interface possible. 

PSST: THIS IS THE FUTURE! AND IT'S ALREADY STEAMROLLING AHEAD WITHOUT YOU!

Just about anything a human specialist can do, a machine can already, or will 
in a short time, do better, faster, and more consistently. This is a fact! We 
humans are terrible at solving problems that require extreme precision, 
repetition, data mining, memory recall, and many other processes that 
computational machines do with great ease. 

Any problem solving process can be broken down into it's atomic components, and 
reassembled as a logical algorithm. Even doctors will soon be replaced with 
machines, which will raise the quality of health care to a level never seen. 
There is almost no skill that is beyond the clutches of the algorithm.

In fact, the only skill that we humans posses which cannot yet be emulated, is 
the power of our imagination. Therefor, our goal should not be to create more 
"specialist", who toil away doing menial tasks like slaves, no, but to foster 
the creative potential of the human mind. 

By first *understanding* algorithmic processes, and then *abstracting* those 
processes in logic form, and finally *relegating* those abstractions to 
computational machines (that expose intuitive interfaces), we will enter an age 
of creative enlightenment such as this world has never seen. Just as the 
information age brought all the worlds knowledge to our fingertips, the 
relegation of menial tasks will free our bodies so that our minds can utilize 
that vast trove of knowledge to drive our technological evolution into 
overdrive. 

And as far as i'm concerned, we can't get there fast enough! 

So if you want to cling to a world where your "special skills" are nothing more 
than "job security", well then, go ahead. As for myself, and the vast majority 
of humanity, we will forge on with or without you!

 SO GOODBYE, AND GOOD RIDDANCE!!!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is vars() the most useless Python built-in ever?

2015-12-04 Thread Serhiy Storchaka

On 02.12.15 11:28, Chris Angelico wrote:

On Wed, Dec 2, 2015 at 7:22 PM, Serhiy Storchaka  wrote:

On 01.12.15 03:00, Steven D'Aprano wrote:

I'm trying to understand why vars() exists. Does anyone use it?

I use vars() exclusively for introspection in interactive environment. As
well as dir() and help(). Sad that it doesn't work with __slots__.

Maybe the upshot of all this is a post to python-ideas recommending
that vars() grow support for __slots__ types? If it's most often used
interactively, this would make it more useful there, and it wouldn't
break backward compatibility unless there's some way that people are
depending on it raising an exception.


It already was discussed few times. And there is even open issue for 
this: http://bugs.python.org/issue13290.



--
https://mail.python.org/mailman/listinfo/python-list


Re: Is vars() the most useless Python built-in ever?

2015-12-02 Thread Albert Visser
On Tue, 01 Dec 2015 22:15:08 +0100, Rick Johnson  
 wrote:



On Tuesday, December 1, 2015 at 10:56:27 AM UTC-6, John Gordon wrote:

Rick Johnson writes:
> Your lament does remind me of a pet peeve i have concerning Python,  
and

> that is, the lie about: "THERE SHOULD BE ONE (AND PREFERABLY ONLY ONE)
> WAY TO DO IT!". In fact, in python there is almost always *MANY* ways  
to

> achieve the same output.=20

The koan reads:

There should be one-- and preferably only one --obvious way to do  
it.


You left out the rather important word "obvious".


Indeed you are correct about the wording, but your interpretation is  
wrong.


Mm, not so much. What you're describing is a statement like "There should  
be one way and it should be obvious".


--
Vriendelijke groeten / Kind regards,

Albert Visser

Using Opera's mail client: http://www.opera.com/mail/
--
https://mail.python.org/mailman/listinfo/python-list


Re: Is vars() the most useless Python built-in ever?

2015-12-02 Thread eryk sun
On Wed, Dec 2, 2015 at 3:28 AM, Chris Angelico  wrote:
> On Wed, Dec 2, 2015 at 7:22 PM, Serhiy Storchaka  wrote:
>>
>> I use vars() exclusively for introspection in interactive environment. As
>> well as dir() and help(). Sad that it doesn't work with __slots__.
>
> Maybe the upshot of all this is a post to python-ideas recommending
> that vars() grow support for __slots__ types? If it's most often used
> interactively, this would make it more useful there, and it wouldn't
> break backward compatibility unless there's some way that people are
> depending on it raising an exception.

Let vars() continue in its antediluvian ways. Maybe the standard
library could add an inspect.getdata function that returns a union of
an object's __dict__ items and data-descriptor attributes.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is vars() the most useless Python built-in ever?

2015-12-02 Thread Chris Angelico
On Wed, Dec 2, 2015 at 9:48 PM, Peter Otten <__pete...@web.de> wrote:
>> I try to do as much as I can with standard library tools. As a user, I
>> find it somewhat off-putting when a tiny project asks you to install any
>> number of seemingly unrelated libraries. But clize does look like a good
>> idea, thanks for the pointer.
>
> Same here ;)

I found out about clize by developing my own module that did the same
job - and then found that, by compromising VERY slightly on some
specifics, I could turn my usage directly to clize :)

One thing I didn't want to compromise on was the simplicity of setup
that I'd had - just slap a decorator onto every function that you want
to make into a callable. So I made my own decorator that collects up
the functions. Total cost: Three lines at the top, two at the bottom
(if name is main, clize.run), and one line per function, plus the
encoded docstring. That's a LOT cheaper than argparse normally is.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is vars() the most useless Python built-in ever?

2015-12-02 Thread Peter Otten
Manolo Martínez wrote:

> On 12/02/15 at 08:33pm, Chris Angelico wrote:
>> On Wed, Dec 2, 2015 at 8:09 PM, Manolo Martínez
>> > This... is true. I could have sworn that's not the way argparse behaved
>> > when I wrote that snippet, but I've been very wrong before about
>> > similar things. Anyway my main() function looks much better now :)
>> 
>> I would recommend not using argparse directly. Pick up a wrapper like
>> clize, and then define everything through docstrings.
>> 
>> Clize usage example:
>> https://github.com/Rosuav/LetMeKnow/blob/master/letmeknow.py
>> 
>> https://pypi.python.org/pypi/clize
> 
> I try to do as much as I can with standard library tools. As a user, I
> find it somewhat off-putting when a tiny project asks you to install any
> number of seemingly unrelated libraries. But clize does look like a good
> idea, thanks for the pointer.

Same here ;)

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is vars() the most useless Python built-in ever?

2015-12-02 Thread Manolo Martínez
On 12/02/15 at 08:33pm, Chris Angelico wrote:
> On Wed, Dec 2, 2015 at 8:09 PM, Manolo Martínez
> > This... is true. I could have sworn that's not the way argparse behaved
> > when I wrote that snippet, but I've been very wrong before about similar
> > things. Anyway my main() function looks much better now :)
> 
> I would recommend not using argparse directly. Pick up a wrapper like
> clize, and then define everything through docstrings.
> 
> Clize usage example:
> https://github.com/Rosuav/LetMeKnow/blob/master/letmeknow.py
> 
> https://pypi.python.org/pypi/clize

I try to do as much as I can with standard library tools. As a user, I
find it somewhat off-putting when a tiny project asks you to install any
number of seemingly unrelated libraries. But clize does look like a good
idea, thanks for the pointer.

Manolo
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is vars() the most useless Python built-in ever?

2015-12-02 Thread Chris Angelico
On Wed, Dec 2, 2015 at 8:09 PM, Manolo Martínez
 wrote:
> Peter Otten wrote:
>> As far as I can see in a correctly written script the AttributeError cannot
>> be triggered by the user as argparse handles this case automatically by
>> showing the help.
>
> This... is true. I could have sworn that's not the way argparse behaved
> when I wrote that snippet, but I've been very wrong before about similar
> things. Anyway my main() function looks much better now :)

I would recommend not using argparse directly. Pick up a wrapper like
clize, and then define everything through docstrings.

Clize usage example:
https://github.com/Rosuav/LetMeKnow/blob/master/letmeknow.py

https://pypi.python.org/pypi/clize

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is vars() the most useless Python built-in ever?

2015-12-02 Thread Chris Angelico
On Wed, Dec 2, 2015 at 7:22 PM, Serhiy Storchaka  wrote:
> On 01.12.15 03:00, Steven D'Aprano wrote:
>>
>> I'm trying to understand why vars() exists. Does anyone use it?
>
>
> I use vars() exclusively for introspection in interactive environment. As
> well as dir() and help(). Sad that it doesn't work with __slots__.

Maybe the upshot of all this is a post to python-ideas recommending
that vars() grow support for __slots__ types? If it's most often used
interactively, this would make it more useful there, and it wouldn't
break backward compatibility unless there's some way that people are
depending on it raising an exception.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is vars() the most useless Python built-in ever?

2015-12-02 Thread Manolo Martínez
Dear Peter, and Steven, thanks again for engaging with my script. I'm
fully aware that this is not the tutor mailing list :)

Peter Otten wrote:
> As far as I can see in a correctly written script the AttributeError cannot 
> be triggered by the user as argparse handles this case automatically by 
> showing the help. 

This... is true. I could have sworn that's not the way argparse behaved
when I wrote that snippet, but I've been very wrong before about similar
things. Anyway my main() function looks much better now :)

> By the way, I recommend coverage.py to find dead code. I have not used
> it for too long, and I regret it ;)

I blush to confess I would first need to write a test suite. But yeah,
will do both, thanks for the recommendation.

Cheers,
Manolo
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is vars() the most useless Python built-in ever?

2015-12-02 Thread Serhiy Storchaka

On 01.12.15 03:00, Steven D'Aprano wrote:

I'm trying to understand why vars() exists. Does anyone use it?


I use vars() exclusively for introspection in interactive environment. 
As well as dir() and help(). Sad that it doesn't work with __slots__.



--
https://mail.python.org/mailman/listinfo/python-list


Re: Is vars() the most useless Python built-in ever?

2015-12-01 Thread Peter Otten
Steven D'Aprano wrote:

> and your code will break. Better and safer is:
> 
> 
> def main():  # parse the args and call whatever function was selected
> args = parser.parse_args(sys.argv[1:])
> try:
> func = args.func
> except AttributeError as err:
> parser.print_help()
> else:
> func(vars(args))

I don't think this is any better. You are reponding on a programming error 
in the script as if the user had provided erroneous input. Very confusing.
Just

args.func(vars(args))

will produce a traceback if the programmer made an error and a help message 
if the user provides arguments that are not recognized. 

That's how it should be.

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is vars() the most useless Python built-in ever?

2015-12-01 Thread Ian Kelly
On Dec 1, 2015 1:36 PM, "Rick Johnson"  wrote:

>

> On Tuesday, December 1, 2015 at 1:55:59 AM UTC-6, Steven D'Aprano wrote:

> > Python was never intended to be "merely" a teaching language. I think

> > Guido's original vision was for it to be a glue language between C

> > libraries, and a scripting language.

>

> It's a well know fact that GvR was inspired to create Python from his
experiences working with a language called ABC -- and ABC was designed
*EXCLUSIVELY* to be a beginners language.

Which is exactly what made ABC itself unsuitable for Guido's purpose, which
was to create an *applications* language with better productivity than C to
support users of Amoeba, the OS that he was working on at the time.

> I am not arguing that "abstractions are evil", no, my position is that
abstractions must be constructed in a manner that provides a clear trail of
bread crumbs which lead to the underlying processes. With print, not only
is the engine in another dimension, but the hood is as well! How is a noob
to discover the engine when he cannot find the hood?

>

> Ponder the following example code (as a noob!):

>

>  stdout.write("Dude, i found my car, the hood, and the effing engine!!!")

>

> Even a noob can intuit what is going on here. First we have an *OBJECT*
named "stdout, and we can extrapolate that stdout is an abbreviation for
StandardOutput. Next, we see a method called "write", and, if our IQ is
above room temperature, then we can extrapolate what that method will do.

This is absurd. You postulate a beginner so rank that they can't understand
what "print" means, yet you expect them to intuitively know:

1) what an object is;

2) what a method is;

3) that a method is identified by placing a period between the object and
the name of the method;

4) what "output" is in the context of programming;

5) and not be confused about what makes the output "standard".

> Now ponder this code (as a noob!):

>

>  print("Dude, where's the intuitiveness?")

>

> What the heck does print do? Where will the string go after i execute
this line of code? Should i turn my printer on? Should i check my ink
levels? And what OEM drivers are required?

You're describing this as if your hypothetical beginner were learning
Python in a vacuum. In reality, people learn from a teacher, or a book, or
at minimum a tutorial.

Here's how you teach somebody what "print" does: instruct them to type
print("hello world") at the interactive prompt. Note that Python writes
"hello world" as a result. If they really want, they can check their
printer and see that nothing came out. That's it. The student now
understands what "print" means.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is vars() the most useless Python built-in ever?

2015-12-01 Thread boB Stepp
On Mon, Nov 30, 2015 at 7:00 PM, Steven D'Aprano  wrote:

>
> Either way, vars() doesn't solve the problem. What problem does it solve?
>

I'm way out of my depth here (I normally post on Tutor, as Steve
knows), but when I looked vars() up in Lutz's "Python Pocket
Reference, 5th ed.", he ended his description of it with:  "... Hint:
useful for referring to variables in string formatting."  This is
probably something obvious to you, but I thought I'd throw it out
there in case it's of any value, since I did not see this mentioned
elsewhere in this thread.  Just trying to learn more ...


-- 
boB
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is vars() the most useless Python built-in ever?

2015-12-01 Thread Ben Finney
Steven D'Aprano  writes:

> You misunderstand the koan.
>
> "There should be one way to do it" does not prohibit more than one
> way.

Further, that's omitting a very important modifier from the koan.

Even without the parenthetical, the koan reads:

There should be one obvious way to do it.

So yes, there can certainly be multiple ways to do it. But it's very
important that there be one *obvious* way.

In other words: Don't present the user with a multitude of options with
no *obvious* choice for those who don't care (yet) to learn about the
choice. Make one of them *obvious* so that's the usually-correct choice.

> (Although having multiple redundant ways is discouraged.) The koan
> exists to encourage the existence of *at least* one (but preferably
> only one) way to do it.

And the Pythonic approach is to make an *obvious* way to do it. As you
say, ‘print’ is that one obvious way for emitting simple text output.

-- 
 \ “What's another word for Thesaurus?” —Steven Wright |
  `\   |
_o__)  |
Ben Finney

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is vars() the most useless Python built-in ever?

2015-12-01 Thread Steven D'Aprano
On Tue, 1 Dec 2015 07:44 pm, Manolo Martínez wrote:

> On 12/01/15 at 12:00pm, Steven D'Aprano wrote:
>> I'm trying to understand why vars() exists. Does anyone use it?
> 
> Well, I have this little podcast aggregator
> (https://github.com/manolomartinez/greg) that I and a bunch of other
> people use. I started writing it some years ago, and the code is a bit
> of a palimpsest, newer functionality reflecting my (somewhat) better
> understanding of the language. One of the oldest bits is this main()
> function:
> 
> def main():  # parse the args and call whatever function was selected
> try:
> args = parser.parse_args(sys.argv[1:])
> args.func(vars(args)) 
> except AttributeError as err:
> if str(err) == "\'Namespace\' object has no attribute \'func\'":
> parser.print_help()
> else:
> print("Something has gone wrong: {}".format(err), 
>   file = sys.stderr, flush = True)
> 
> 
> To judge by this thread, this is probably wrong/noobish?

I've seen worse :-)

Checking the error message in that way is risky. As an absolute last resort,
I guess it works, but it's hack-ish (not in a good way) and fragile. The
problem is, error messages are not part of the Python API and are subject
to change without warning.

(Aside: when I design my language, I'm going to ensure that error messages
vary from one exception to the next, specifically to discourage this :-)

Today, you get an error message 

"'Namespace' object has no attribute 'func'"

(note that there is no need to escape the single quotes) but there's no
guarantee that this will always be the same. Tomorrow it could silently
change to:

'"Namespace" instance does not have a "func" attribute.'

and your code will break. Better and safer is:


def main():  # parse the args and call whatever function was selected
args = parser.parse_args(sys.argv[1:])
try:
func = args.func
except AttributeError as err:
parser.print_help()
else:
func(vars(args))



-- 
Steven

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is vars() the most useless Python built-in ever?

2015-12-01 Thread Steven D'Aprano
On Wed, 2 Dec 2015 07:33 am, Rick Johnson wrote:

> On Tuesday, December 1, 2015 at 1:55:59 AM UTC-6, Steven D'Aprano wrote:
>> Python was never intended to be "merely" a teaching language. I think
>> Guido's original vision was for it to be a glue language between C
>> libraries, and a scripting language.
> 
> It's a well know fact that GvR was inspired to create Python from his
> experiences working with a language called ABC -- and ABC was designed
> *EXCLUSIVELY* to be a beginners language. 

Certainly. But do you have any evidence that *Python* was designed to be
exclusively a beginner's language?

It is possible to be inspired by a teaching language without aiming to be
limited to the functionality of a teaching language.


>> > Rick said:
>> > (1) How do you output a message without the print function?
>> 
> Steven said:
>> *scratches head*
>> 
>> Why would you want to do that? print is clearly the "one obvious way" to
>> output a message.
> 
> Well of course the answers are *OBVIOUS* when you already *KNOW* them
> Steven! Climb down off your high horse for a moment, and take yourself
> back to a time *BEFORE* you had any knowledge of output streams.

What's an output stream?

All I know is that if you want to print a message, calling "print" is the
obvious way to do it. Using the word "print" for writing text on the screen
is very common, although not ubiquitous. Rosetta Code includes over 300
examples of the "Hello World" program, and a quick glance at the page shows
that (apart from deliberately obfuscatory languages and assembly
languages), print is one of the more common functions used:

http://rosettacode.org/wiki/Hello_world/Text

Others include:

echo
puts
write
writeln
printf
println
display
console.log
cout
say
System.Console.WriteLine

which vary in their obviousness.



[...]
> Ponder the following example code (as a noob!):
> 
>  stdout.write("Dude, i found my car, the hood, and the effing engine!!!")
> 
> Even a noob can intuit what is going on here. First we have an *OBJECT*
> named "stdout, and we can extrapolate that stdout is an abbreviation for
> StandardOutput. Next, we see a method called "write", and, if our IQ is
> above room temperature, then we can extrapolate what that method will do.

Are you serious? You think that a complete beginner to programming is going
to have an intuitive grasp of stdout? What did you say earlier about
putting aside my knowledge of output streams?


> Now ponder this code (as a noob!):
> 
>  print("Dude, where's the intuitiveness?")
> 
> What the heck does print do? 

It's a standard English word, and has been since at least 1469, and possibly
as long ago as 1150. As a native English speaker, I'm surprised that your
vocabulary is so lacking that you need help with that, especially as an
American. Didn't they teach you "printing" (block letters) and "cursive"
(joined up letters) handwriting when you were at school?



> Where will the string go after i execute this 
> line of code? Should i turn my printer on? Should i check my ink levels?
> And what OEM drivers are required?

That's an interesting point. In, oh, a dozen or more years of dealing with
Python beginners, I have come across *exactly one* beginner who assumed
that print would send output to the printer. 

Where there's one, there are probably more, but I think it is fair to say
that the idea of *printing to the screen* is commonplace, and these days
probably even more common than the idea of printing to paper. I expect that
kids learning BASIC in the 1970s probably had more difficulty with the
concept, but even then, that difficulty would extend to as long as it takes
somebody to say "it prints the message to the screen".


> Not only is "print" un-intuitive (by nature of it's naming), it is
> obfuscating the path to the underlying process of "sending data to an
> output stream".

A wise man once said to me, "take yourself back to a time *BEFORE* you had
any knowledge of output streams". Although I suspect perhaps he was more of
a wise guy than a wise man.



-- 
Steven

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is vars() the most useless Python built-in ever?

2015-12-01 Thread Gregory Ewing

Rick Johnson wrote:

the lie about: "THERE SHOULD BE ONE (AND PREFERABLY ONLY ONE) WAY TO DO
IT!".


You're misquoting the Zen. It says there should be one
*obvious* way to do it.

--
Greg
--
https://mail.python.org/mailman/listinfo/python-list


Re: Is vars() the most useless Python built-in ever?

2015-12-01 Thread Peter Otten
Manolo Martínez wrote:

> Peter, thanks for taking the time to look into my code.
> 
> On 12/01/15 at 11:40am, Peter Otten wrote:
>> Manolo Martínez wrote:
>> > def main():  # parse the args and call whatever function was
>> selected
>> > try:
>> > args = parser.parse_args(sys.argv[1:])
>> > args.func(vars(args))
>> > except AttributeError as err:
>> > if str(err) == "\'Namespace\' object has no
>> attribute \'func\'":
>> > parser.print_help()
>> > else:
>> > print("Something has gone wrong:
>> {}".format(err), file = sys.stderr, flush = True)
>> 
>> What probably is typical for a beginner in that snippet is that you don't
>> trust the exception system and handle exceptions that will never occur
>> once the script is debugged. Just write
>> 
>> args = parser.parse_args()
>> args.func(vars(args))
> 
> Well, one fully possible situation is for the user to mistype a
> subcommand. In that case, the script outputs the help provided by
> argparse, so that they know what is and isn't meaningful. That is what
> the "if str(err)..." is doing.
> 
> The else clause is there to output the traceback (in full trust of the
> exception system ;) in case the error was not due to the user mistyping.
> 
> Is there a better way to do this?

As far as I can see in a correctly written script the AttributeError cannot 
be triggered by the user as argparse handles this case automatically by 
showing the help. For example:

$ cat subparsers.py
#!/usr/bin/env python3
import argparse


def foo(args):
print(args)


def main():
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()

foo_parser = subparsers.add_parser("foo")
foo_parser.set_defaults(func=foo)

bar_parser = subparsers.add_parser("bar")
# programming error --> missing func attribute

args = parser.parse_args()
args.func(args)


main()
$ ./subparsers.py foo
Namespace(func=)
$ ./subparsers.py bar
Traceback (most recent call last):
  File "./subparsers.py", line 23, in 
main()
  File "./subparsers.py", line 20, in main
args.func(args)
AttributeError: 'Namespace' object has no attribute 'func'
$ ./subparsers.py baz # erroneous user input
usage: subparsers.py [-h] {foo,bar} ...
subparsers.py: error: invalid choice: 'baz' (choose from 'foo', 'bar')

The traceback may be a bit intimidating, but with your error handling the 
user will get

$ cat subparsers2.py
#!/usr/bin/env python3
import argparse


def foo(args):
print(args)


def main():
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()

foo_parser = subparsers.add_parser("foo")
foo_parser.set_defaults(func=foo)

bar_parser = subparsers.add_parser("bar")
# programming error --> missing func attribute


try:
args = parser.parse_args()
args.func(args)
except AttributeError as err:
if str(err) == "\'Namespace\' object has no attribute \'func\'":
print("WE ARE HERE")
parser.print_help()
else:
print("Something has gone wrong: {}".format(err), file = 
sys.stderr, flush = True)

main()
$ ./subparsers2.py foo
Namespace(func=)
$ ./subparsers2.py baz # erroneous user input does not trigger your error 
handling
usage: subparsers2.py [-h] {foo,bar} ...
subparsers2.py: error: invalid choice: 'baz' (choose from 'foo', 'bar')
$ ./subparsers2.py bar # but an error in your script does
WE ARE HERE
usage: subparsers2.py [-h] {foo,bar} ...

positional arguments:
  {foo,bar}

optional arguments:
  -h, --help  show this help message and exit

which is very confusing. Again, don't replace the traceback unless you are 
absolutely sure you can do better than the Python interpreter.

By the way, I recommend coverage.py to find dead code. I have not used it 
for too long, and I regret it ;)



-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is vars() the most useless Python built-in ever?

2015-12-01 Thread Manolo Martínez
Peter, thanks for taking the time to look into my code.

On 12/01/15 at 11:40am, Peter Otten wrote:
> Manolo Martínez wrote:
> > def main():  # parse the args and call whatever function was 
> selected
> > try:
> > args = parser.parse_args(sys.argv[1:])
> > args.func(vars(args))
> > except AttributeError as err:
> > if str(err) == "\'Namespace\' object has no 
> attribute \'func\'":
> > parser.print_help()
> > else:
> > print("Something has gone wrong: 
> {}".format(err), file = sys.stderr, flush = True)
> 
> What probably is typical for a beginner in that snippet is that you don't 
> trust the exception system and handle exceptions that will never occur once 
> the script is debugged. Just write
> 
> args = parser.parse_args()
> args.func(vars(args))

Well, one fully possible situation is for the user to mistype a
subcommand. In that case, the script outputs the help provided by
argparse, so that they know what is and isn't meaningful. That is what
the "if str(err)..." is doing.

The else clause is there to output the traceback (in full trust of the
exception system ;) in case the error was not due to the user mistyping.

Is there a better way to do this?

> Now vars(). I see nothing wrong with it, but when I look into one of your 
> func implementations
> 
> > def info(args):  # Provides information of a number of feeds
> > session = Session(args)
> > if "all" in args["names"]:
> > feeds = session.list_feeds()
> > else:
> > feeds = args["names"]
> > for feed in feeds:
> > pretty_print(session, feed)
> 
> I come to the conclusion that passing args directly could make your life 
> easier:
> 
> def info(args):  
> """Provides information of a number of feeds"""
> session = Session(args)
> if "all" in args.names:
> feeds = session.list_feeds()
> else:
> feeds = args.names
> for feed in feeds:
> pretty_print(session, feed)
> 
> As far as I can see there is only one place where the key is not a constant, 
> and you can rewrite that from 
> 
> > try:
> > if args[value]:
> > return args[value]
> > except KeyError:
> > pass
> 
> to
> 
> try:
> answer = getattr(args, value)
> if answer: 
> return answer
> except AttributeError:
> pass
> 

This is very helpful, thanks a lot! 

Manolo
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is vars() the most useless Python built-in ever?

2015-12-01 Thread Rick Johnson
On Tuesday, December 1, 2015 at 10:56:27 AM UTC-6, John Gordon wrote:
> Rick Johnson writes:
> > Your lament does remind me of a pet peeve i have concerning Python, and
> > that is, the lie about: "THERE SHOULD BE ONE (AND PREFERABLY ONLY ONE)
> > WAY TO DO IT!". In fact, in python there is almost always *MANY* ways to
> > achieve the same output.=20
> 
> The koan reads:
> 
> There should be one-- and preferably only one --obvious way to do it.
> 
> You left out the rather important word "obvious".

Indeed you are correct about the wording, but your interpretation is wrong. In 
fact, adding the word "obvious" only adds more truth to my argument. The word 
"obvious" does not imply that the choose method is "one *OBVIOUS* choice in a 
set of many choices", no, the word obvious merely implies intuitiveness. Let's 
dissect the "koan" component by component:

  "There should be one"

This component is less of a request, and more of a demand. It seems the author 
wishes to stress that whatever follows, there should only be one of them.
 
  "and preferably only one"

Interesting. Utilizing his advanced intellect, the author realizes that 
confining any set of choices to a length of one is not always possible, 
however, he *AGAIN* stresses the importance of length one! I'm beginning to see 
a common and obvious theme here, do you?

  "obvious way to do it"

And finally we encounter the obviousness of the one chosen way!  

The three components can be summarized as follows: First he demands a length of 
one, then he allows for exceptions while again stressing the importance of 
"one", and finally he stresses the importance of intuitiveness by using the 
word "obvious". 

In *NONE* of these components does the author *ENCOURAGE* a set of choices, no, 
he consistently stresses the importance of "one". And although it seems he has 
lost his will within the middle component (by entertaining the "unpreferred" 
possibility of more than one choice) he did not do so because his argument for 
"one" is weak, rather because, he knows that conflict and contrarianism is 
inevitable in a world that is ruled by selfish hairless apes! He has both 
demanded, and made an impassioned plea for, the "one obvious way" to do it. Any 
other interpretation is pure emotional projection.

PS: Now that I've defeated the claim that "the koan is encouraging more than 
one way", as a last resort, they will dismiss the koan as unimportant. This is 
not my first experience here folks!!!

PPS: Koan must be word of the day.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is vars() the most useless Python built-in ever?

2015-12-01 Thread Rick Johnson
On Tuesday, December 1, 2015 at 1:55:59 AM UTC-6, Steven D'Aprano wrote:
> Python was never intended to be "merely" a teaching language. I think 
> Guido's original vision was for it to be a glue language between C 
> libraries, and a scripting language.

It's a well know fact that GvR was inspired to create Python from his 
experiences working with a language called ABC -- and ABC was designed 
*EXCLUSIVELY* to be a beginners language. GvR has even written that one of his 
objections to ABC's design was it's tendency to create new jargon-isms to 
replace old jargon-isms. The language designers "thought" they could ease the 
learning curve simply thru virtue of symbols, but all they did was to further 
confuse noobs. GvR saw the folly of this, and set out to prevent such design 
flaws in his language, however, i argue that interfaces like the "print 
function" are making the same mistakes. The linking of abstraction layers  is 
even *MORE* important than intuitive naming conventions. But sometimes the name 
is the only path by which you can provide the link. As is the case with the 
print function.

> > Rick said:
> > (1) How do you output a message without the print function?
> 
Steven said:
> *scratches head*
> 
> Why would you want to do that? print is clearly the "one obvious way" to 
> output a message.

Well of course the answers are *OBVIOUS* when you already *KNOW* them Steven! 
Climb down off your high horse for a moment, and take yourself back to a time 
*BEFORE* you had any knowledge of output streams. 

I am not arguing that "abstractions are evil", no, my position is that 
abstractions must be constructed in a manner that provides a clear trail of 
bread crumbs which lead to the underlying processes. With print, not only is 
the engine in another dimension, but the hood is as well! How is a noob to 
discover the engine when he cannot find the hood?

Ponder the following example code (as a noob!):

 stdout.write("Dude, i found my car, the hood, and the effing engine!!!")

Even a noob can intuit what is going on here. First we have an *OBJECT* named 
"stdout, and we can extrapolate that stdout is an abbreviation for 
StandardOutput. Next, we see a method called "write", and, if our IQ is above 
room temperature, then we can extrapolate what that method will do.

Now ponder this code (as a noob!):

 print("Dude, where's the intuitiveness?")

What the heck does print do? Where will the string go after i execute this line 
of code? Should i turn my printer on? Should i check my ink levels? And what 
OEM drivers are required?

Not only is "print" un-intuitive (by nature of it's naming), it is obfuscating 
the path to the underlying process of "sending data to an output stream".
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is vars() the most useless Python built-in ever?

2015-12-01 Thread John Gordon
In <4f0f7fc5-c93a-4223-9c05-e192a8faf...@googlegroups.com> Rick Johnson 
 writes:

> Your lament does remind me of a pet peeve i have concerning Python, and
> that is, the lie about: "THERE SHOULD BE ONE (AND PREFERABLY ONLY ONE)
> WAY TO DO IT!". In fact, in python there is almost always *MANY* ways to
> achieve the same output.=20

The koan reads:

There should be one-- and preferably only one --obvious way to do it.

You left out the rather important word "obvious".

-- 
John Gordon   A is for Amy, who fell down the stairs
gor...@panix.com  B is for Basil, assaulted by bears
-- Edward Gorey, "The Gashlycrumb Tinies"

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is vars() the most useless Python built-in ever?

2015-12-01 Thread Peter Otten
Manolo Martínez wrote:

> On 12/01/15 at 12:00pm, Steven D'Aprano wrote:
> > I'm trying to understand why vars() exists. Does anyone use it?
> 
> Well, I have this little podcast aggregator
> (https://github.com/manolomartinez/greg) that I and a bunch of other
> people use. I started writing it some years ago, and the code is a bit
> of a palimpsest, newer functionality reflecting my (somewhat) better
> understanding of the language. One of the oldest bits is this main()
> function:
> 
> def main():  # parse the args and call whatever function was 
selected
> try:
> args = parser.parse_args(sys.argv[1:])
> args.func(vars(args))
> except AttributeError as err:
> if str(err) == "\'Namespace\' object has no 
attribute \'func\'":
> parser.print_help()
> else:
> print("Something has gone wrong: 
{}".format(err), file = sys.stderr, flush = True)
>  
> 
> To judge by this thread, this is probably wrong/noobish?

What probably is typical for a beginner in that snippet is that you don't 
trust the exception system and handle exceptions that will never occur once 
the script is debugged. Just write

args = parser.parse_args()
args.func(vars(args))

Now vars(). I see nothing wrong with it, but when I look into one of your 
func implementations

> def info(args):  # Provides information of a number of feeds
> session = Session(args)
> if "all" in args["names"]:
> feeds = session.list_feeds()
> else:
> feeds = args["names"]
> for feed in feeds:
> pretty_print(session, feed)

I come to the conclusion that passing args directly could make your life 
easier:

def info(args):  
"""Provides information of a number of feeds"""
session = Session(args)
if "all" in args.names:
feeds = session.list_feeds()
else:
feeds = args.names
for feed in feeds:
pretty_print(session, feed)

As far as I can see there is only one place where the key is not a constant, 
and you can rewrite that from 

> try:
> if args[value]:
> return args[value]
> except KeyError:
> pass

to

try:
answer = getattr(args, value)
if answer: 
return answer
except AttributeError:
pass


-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is vars() the most useless Python built-in ever?

2015-12-01 Thread Manolo Martínez
On 12/01/15 at 12:00pm, Steven D'Aprano wrote:
> I'm trying to understand why vars() exists. Does anyone use it?

Well, I have this little podcast aggregator
(https://github.com/manolomartinez/greg) that I and a bunch of other
people use. I started writing it some years ago, and the code is a bit
of a palimpsest, newer functionality reflecting my (somewhat) better
understanding of the language. One of the oldest bits is this main()
function:

def main():  # parse the args and call whatever function was selected
try:
args = parser.parse_args(sys.argv[1:])
args.func(vars(args))
except AttributeError as err:
if str(err) == "\'Namespace\' object has no attribute 
\'func\'":
parser.print_help()
else:
print("Something has gone wrong: 
{}".format(err), file = sys.stderr, flush = True)
 

To judge by this thread, this is probably wrong/noobish?

Cheers,
Manolo
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is vars() the most useless Python built-in ever?

2015-12-01 Thread Steven D'Aprano
On Tuesday 01 December 2015 18:22, eryk sun wrote:

> On Mon, Nov 30, 2015 at 7:00 PM, Steven D'Aprano 
> wrote:
>> Either way, vars() doesn't solve the problem. What problem does it solve?
> 
> vars() used to be the way to list local variables.

Oh, snap! Nice bit of detective work. So it's basically a left-over from 
when dinosaurs roamed the earth.



-- 
Steve

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is vars() the most useless Python built-in ever?

2015-12-01 Thread Steven D'Aprano
On Tuesday 01 December 2015 16:54, Rick Johnson wrote:

> On Monday, November 30, 2015 at 7:01:14 PM UTC-6, Steven D'Aprano wrote:
>> I'm trying to understand why vars() exists. Does anyone use it?
> 
> I think your "mental dilemma" stems from the fact that python was
> originally created to be an easy language for noobs to learn (which it
> still mostly is), 

Python was never intended to be "merely" a teaching language. I think 
Guido's original vision was for it to be a glue language between C 
libraries, and a scripting language.


> however, over the years, feature creep has expanded this
> small general purpose language to include many specific applications. The
> "vars" function is a relic of the early days of Python and has not evolved
> because 99% of Python hackers find it to be useless. I mean, heck, print
> did not evolve until Py3! Outside of a few test sessions in my early days
> with Python, I don't remember ever using the vars function again.
> 
> Your lament does remind me of a pet peeve i have concerning Python, and
> that is, the lie about: "THERE SHOULD BE ONE (AND PREFERABLY ONLY ONE) WAY
> TO DO IT!". In fact, in python there is almost always *MANY* ways to
> achieve the same output.

You misunderstand the koan.

"There should be one way to do it" does not prohibit more than one way. 
(Although having multiple redundant ways is discouraged.) The koan exists to 
encourage the existence of *at least* one (but preferably only one) way to 
do it.

"It", of course, is not defined, as if fitting for a koan. (Koans are meant 
to make you think, and they also act as a way of separating the adults from 
the kiddies -- do you have the experience to grok the meaning of the koan?

For example, some people have been fooled by the apparent similarity of 
globals(), locals(), dir(), __dict__ and vars(), thinking that this is five 
ways to do the same thing, right? But no.

(1) globals() *always* returns the global namespace.

(2) locals() *always* returns the local namespace. It just happens that 
sometimes the local and global namespaces are the same.

(3) dir() is intended as a user-friendly introspection tool at the 
interactive interpreter. As a result, it is permitted to modify the list of 
names returned, and in fact it does, suppressing some names which the core 
developers deem insufficiently "interesting".

(4) __dict__ (in the sense of obj.__dict__) is the implementation, not part 
of Python's high-level interface. Attributes have to be stored somewhere, 
and Python chooses to reveal that in the documentation, nevertheless if you 
find yourself writing "__dict__" in production code, you're probably doing 
something wrong.


These three functions, and one attribute, are clearly related, but they are 
just as clearly solutions to four distinct problems. There may be a little 
overlap, but at their core, the "it" that they are the way to "do it" are 
very different things.

Which brings us to #5, vars():

"What is vars() good for?" is exactly what I'm asking. It seems to be the 
high-level interface to the implementation detail of __dict__, but I'm not 
sure that's needed. When that implementation changes -- classes using 
__slots__ instead of a dictionary -- we should expect that the high-level 
interface should adapt, otherwise what's the point of it? But it doesn't.

vars() also defaults to returning locals() for no good reason I can see. 
Whatever the "it" is that vars() is meant to do is a good question, but it 
clearly isn't the same "it" as that for globals(), locals() and dir().


> We may find this difficult to believe, but many a noob has been stumped by
> the following questions:
> 
> (1) How do you output a message without the print function?

*scratches head*

Why would you want to do that? print is clearly the "one obvious way" to 
output a message.



-- 
Steve

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is vars() the most useless Python built-in ever?

2015-11-30 Thread Marko Rauhamaa
Rick Johnson :

> python was originally created to be an easy language for noobs to
> learn

Really? That's would be a silly objective for a programming language.

> many a noob has been stumped

So?

You have to first placate the experts and the "noobs" will follow.


Marko
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is vars() the most useless Python built-in ever?

2015-11-30 Thread eryk sun
On Mon, Nov 30, 2015 at 7:00 PM, Steven D'Aprano  wrote:
> Either way, vars() doesn't solve the problem. What problem does it solve?

vars() used to be the way to list local variables.

>From 4 May 1994, Python 1.0.2 [1]:

vars() returns a dictionary containing the local variables;
vars(m) returns a dictionary containing the variables of
module m.  Note: dir(x) is now equivalent to
vars(x).keys().

>From 13 October 1995, Python 1.3 [2]:

Two new built-in functions, "globals()" and "locals()",
provide access to dictionaries containming [sic] current
global and local variables, respectively.  (These
augment rather than replace "vars()", which returns the
current local variables when called without an argument,
and a module's global variables when called with an
argument of type module.)

[1]: https://hg.python.org/cpython/file/v1.3/Misc/HISTORY#l386
[2]: https://hg.python.org/cpython/file/v1.3/Misc/NEWS#l55
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is vars() the most useless Python built-in ever?

2015-11-30 Thread Rick Johnson
On Monday, November 30, 2015 at 7:01:14 PM UTC-6, Steven D'Aprano wrote:
> I'm trying to understand why vars() exists. Does anyone use it?

I think your "mental dilemma" stems from the fact that python was originally 
created to be an easy language for noobs to learn (which it still mostly is), 
however, over the years, feature creep has expanded this small general purpose 
language to include many specific applications. The "vars" function is a relic 
of the early days of Python and has not evolved because 99% of Python hackers 
find it to be useless. I mean, heck, print did not evolve until Py3! Outside of 
a few test sessions in my early days with Python, I don't remember ever using 
the vars function again. 

Your lament does remind me of a pet peeve i have concerning Python, and that 
is, the lie about: "THERE SHOULD BE ONE (AND PREFERABLY ONLY ONE) WAY TO DO 
IT!". In fact, in python there is almost always *MANY* ways to achieve the same 
output. 

For instance, consider the output of vars(), globals(), locals(), dir(), and 
obj.__dict__. In many cases, all of these, or at least most of these, will 
return the same answer(s). Not only is that type of interface repetitive, it 
superfluously obfuscates the underling paths by which the value is obtained. 

We may find this difficult to believe, but many a noob has been stumped by the 
following questions:

(1) How do you output a message without the print function?

(2) How do you fetch a listing of an object's methods without the dir function?

Listen, there is nothing wrong with creating "layers of abstraction". In fact, 
without abstractions, we could not evolve our technologies, however, if these 
"layers" are not intentionally crafted in logical order, then we quickly move 
away from the intuitive structure of a "cake model" and into the dreaded 
nightmare of the "spaghetti model". We should strive to structure our code in 
the image of a MandelBot set (think: "levels of detail"), not a hedge maze 
labyrinth of an "Overlook Hotel"!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is vars() the most useless Python built-in ever?

2015-11-30 Thread Josef Pktd
On Monday, November 30, 2015 at 8:01:14 PM UTC-5, Steven D'Aprano wrote:
> I'm trying to understand why vars() exists. Does anyone use it?
> 
> Every time I try to use it, I find it doesn't quite do what I want. And even
> if it did, there are more obvious and/or correct alternatives.
> 
> For instance, I want to check whether a particular name is an instance
> attribute. So first I write:
> 
> "name" in obj.__dict__
> 
> but when I see the dunder name I think that's an implementation detail. And
> sure enough, not all instances have a __dict__ (e.g. if it uses __slots__
> instead) and so I re-write it as:
> 
> "name" in vars(obj)
> 
> but that also fails if obj has no instance __dict__.
> 
> But why am I looking just in the instance __dict__? Chances are I should be
> looking for the attribute *anywhere* in the instance/class/superclass
> hierarchy: 
> 
> hasattr(obj, "name")
> 
> Or, if you are worried about triggering dynamic attributes using
> __getattr__, you can do this:
> 
> sentinel = object()
> inspect.getattr_static(obj, "name", sentinel) is not sentinel
> 
> which only checks for pre-existing attributes without triggering
> __getattr__, __getattribute__, or the descriptor protocol.
> 
> 
> Either way, vars() doesn't solve the problem. What problem does it solve?

I'm using dir and vars pretty often when I'm trying to figure out new code or 
review a pull request, or when I'm reviewing code that I don't remember.

Both are convenient for quickly checking which attributes are available at the 
moment. I never realized that there might be issues with "fancy" problems. 

`vars` is convenient, for example, to check which attributes have been 
initialized to None, and which already have assigned values. And checking again 
after some calculations, I roughly see which attributes have been added or 
changed in the mean time.

aside: I'm boring and like code that has no magic, especially if I have to 
maintain it.

Josef

> 
> 
> 
> -- 
> Steven

-- 
https://mail.python.org/mailman/listinfo/python-list