Re: The "loop and a half"

2017-10-07 Thread Steve D'Aprano
On Sat, 7 Oct 2017 11:05 am, bartc wrote:

> On 07/10/2017 00:43, Steve D'Aprano wrote:
>> On Sat, 7 Oct 2017 12:24 am, bartc wrote:
>> 
>>> print ("Enter blank expression to quit.")
>> 
>> 
>> I *despise* programs that do that, and would cheerfully and
>> unapologetically take their designers, disguise them as a lettuce, and
>> stake them out to be nibbled to death by snails.
>> 
>> At the interactive prompt, I am frequently hitting Enter on a blank line,
>> either by accident, or deliberately to break up the calculations into
>> groups, or just to give myself time to think.
>> 
>> Blank lines should be treated as "do nothing" and simply ignored, and there
>> should be an explicit QUIT command.
> 
> 
> Um, that actually follows what interactive Python does.


What is "that" to which you refer?

If you mean, "what I, Bart C, suggested, namely having the program exit on a
blank line", then you are wrong. In the Python interactive interpreter, you
can enter blank lines, and the interpreter doesn't exit.

If you mean "what Steven suggests, namely ignoring blank lines and requiring
either an explicit EOF (Ctrl-D on Unix) or quit() or exit() command to exit",
then you are correct, Python does do that.

There's one priviso: blank lines are only ignored at the primary prompt >>>
not the secondary prompt ... where a blank line is used to end the block. But
the interpreter doesn't exit. A slight compromise for the sake of convenience
at the interactive prompt.


> (Most of my real interactive programs with a command line interface
> programs use Escape, quit, exit, q or x to finish.

And how do you distinguish between calling quit from inside the function, and
using quit inside the function?

def foo():
pass
quit
# or exit, q or x for that matter

would be a perfectly legal (although rather pointless) function.

If typing the letter x alone was enough to exit the block, how do you type
`x=1` when the instance you press `x` the interpreter helpfully exits the
block?

If you require `x` followed by ENTER, then that prohibits legal lines which
consist of nothing but `x`.

Unfortunately ESCAPE is already used. VT100 (the terminal emulation which is
used in just about all terminals) all control sequences begin with ESC. So
every time you do something like press an arrow key, the terminal sends ESC
followed by other stuff. It would be painful if every time you hit an arrow
key, the interpreter took it as "Exit".


> Interactive Python requires quit() or exit(), complete with parentheses.
> Unless you've redefined quit and exit as something else, then you have
> to crash out by other means.)

"Crash out", he says.

If your intention is to prove that you're a know-nothing ignoramus, you're
doing an excellent job of it.

 

-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

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


Re: Interactive scripts (back on topic for once) [was Re: The "loop and a half"]

2017-10-07 Thread Steve D'Aprano
On Sat, 7 Oct 2017 12:12 am, Paul Moore wrote:

> What really bugs me is colour settings that default to dark blues on
> a black background.

Amen to that!

Between the very low contrast, and the stereopsis whereby blues appear to
recede into the distance (and bright red pull forward, appearing to float on
top of the terminal), dark blue text on the background is nearly unreadable.

https://en.wikipedia.org/wiki/Chromostereopsis


[...]
> Add the fact that
> I work on shared admin accounts, where setting non-default preferences
> is considered an antisocial act (even when they are "better" ;-)) and
> I spend my life squinting at screens, or typing "unalias ls" to remove
> the --color setting. Luckily (for everyone who has to listen to me
> rant), this is "just" annoyingly badly configured systems, and not
> baked in program defaults.

At my previous job, the solution to that was to ban changing the default
settings, but allow admins to create their own personalised defaults.

Fred would log in to the shared account, and run 

source fred

to get his personalised settings. When George logged in to the shared account,
he'd see the defaults, not Fred's settings, and could run

source george

to get his own settings.

(Obviously Fred and George would have to create the "fred" and "george" config
files first.)

I don't know if Windows shells have something like bash's `source` command,
but if it does, this would be one solution.


-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

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


Re: Introducing the "for" loop

2017-10-07 Thread Steve D'Aprano
On Fri, 6 Oct 2017 11:44 pm, ROGER GRAYDON CHRISTMAN wrote:

> Despite the documentation, I would still be tempted to say that range is a
> function.
> Taking duck-typing to the meta-level, every time I use range, I use its name
> followed
> by a pair of parentheses enclosing one to three parameters, and I get back
> an
> immutable sequence object.   It sure looks like a function to me.

I agree -- range() is a function in the (almost) mathematical sense, something
which takes arguments and returns a value. It's also a type (class), in the
OOP sense:


py> type(range)



The term "function" is ambiguous but normally clear from context. Often, the
differences make no difference, but when they are important, we can discuss
them:

- range is a callable (a callable object);

- it is also a type/class, and calling it returns an instance;

- it looks like, and behaves like, a function;

- and is, conceptually, a function;

- but it is *not* an instance of FunctionType:


py> from types import FunctionType
py> def function():
... pass
...
py> isinstance(function, FunctionType)
True
py> isinstance(range, FunctionType)
False


It is this last sense (an instance of FunctionType) which people are thinking
of when they state that range is not a function.



-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

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


Re: Interactive scripts (back on topic for once) [was Re: The "loop and a half"]

2017-10-07 Thread Terry Reedy

On 10/6/2017 8:19 PM, Steve D'Aprano wrote:

On Sat, 7 Oct 2017 05:33 am, Grant Edwards wrote:


On 2017-10-06, Marko Rauhamaa  wrote:


The reason a daemon usually opens dummy file descriptors for the 0, 1
and 2 slots is to avoid accidents. Some library might assume the
existence of those file descriptors. For example, I often see GTK print
out diagnositic messages.


I run a lot of GTK programs from the command line, and I would say 90%
or more of them spew a steady stream of meaningless (to the user)
diagnostic messages.  That's pretty sloppy programming if you ask
me...


Indeed.

If you ever start to doubt that the average quality of software is "crap", try
running GUI applications from the command line and watch the stream of
warnings and errors flow by. They range from relatively trivial warnings that
correctly sized icons are missing, to scary looking warnings about
uninitialised pointers.


IDLE does not do that because tkinter and the other stdlib modules it 
uses does not do that.  There are occasionally extraneous messages from 
tcl when shutting down.



Developers: why do you bother to log warnings if you're never going to fix the
damn things?

They're probably to busy re-doing working programs from scratch every few
versions, with a brand new "improved" UI (almost invariably including a kool
new design that uses light grey text on an ever so slightly lighter grey
background) and deleting any useful functionality that the lead developer
personally doesn't use, because "nobody uses that".

https://www.jwz.org/doc/cadt.html






--
Terry Jan Reedy

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


Re: The "loop and a half"

2017-10-07 Thread Steve D'Aprano
On Sat, 7 Oct 2017 07:01 am, bartc wrote:

> On 06/10/2017 20:38, Grant Edwards wrote:
>> On 2017-10-06, bartc  wrote:
>> 
>>> For sort, there is no real need. You use a text editor to create
>>> your data. Then use existing file-based sort.
>> 
>> I sort streams on stdin far more often than I sort named files.
> 
> So what's been established is that 'sort' is useful for a text stream
> that already exists as a file or is the output of another process.

Indeed. And "another process" can just as easily be a human at the keyboard,
although we must keep in mind the primitive line-oriented editing facilities
of stdin (basically backspace and that's it).

 
> What hasn't been established is why how this works this has to influence
> the design of simple text-based dialogues, real ones where there will
> likely be an actual user tapping the keys in real time.

Obviously it doesn't, and as far as I can see, nobody has suggested that such
primitive facilities should be treated as the archetype of *user-oriented*
application programming. There are other kinds of programs than those aimed
primarily at direct use by users.

As I interpret what people have been saying in this thread, the claim is far
more modest:

- sort is designed for use in pipelines, as a typical Unix tool;

- the way to exit sort is the same way you exit pretty much everything
  in the Unix command line, using EOF (Ctrl-D);

- Unix admins and even Unix end users learn Ctrl-D just as Windows users
  learn ESC and Ctrl-Q and Alt-F4 and the other myriad standard ways to
  exit an application in the Windows world;

- as a Unix tool rather than a text-based application with a rich
  user-interface, it doesn't need verbose output, introduction messages, 
  help screens, and all the other bells and whistles;

- although there is a valid argument to be made that sort could be a little
  more user-friendly in interactive use without badly compromising its 
  primary purpose. But that's a matter of taste.


Besides, we know what the nirvana of user-interfaces should look like:

https://www.gnu.org/fun/jokes/ed-msg.html



> The only tenuous connection I can see, is that if 'sort' is run without
> any piped or redirected input, it will resort to the keyboard.

It doesn't "resort to the keyboard", that's just how stdin works.

If you have a car built to drive on roads, and you drive it up onto the lawn,
the car doesn't need a special mode that detects the missing road
and "resorts to driving on the lawn". It just happens. Stdin is like that.




> Even though that method is not user-friendly 

True enough. `sort` is not designed to be a end-user application, although it
can be used by the end-user.


> and hardly anyone ever uses it in that mode.

Translation: "I don't use it in that mode".


> So that same unfriendly technique should be the model for 
> text dialogues everywhere.

I'm pretty sure that nobody said that.




-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

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


Re: Warnings (was Re: Interactive scripts (back on topic for once) [was Re: The "loop and a half"])

2017-10-07 Thread Steve D'Aprano
On Sat, 7 Oct 2017 12:09 pm, Chris Angelico wrote:

> So the question is: is it right for a library to raise
> console warnings like that? Under what circumstances and to what
> destinations should a library report on potential problems?

Of course they should -- and applications should be free to disable the
warnings.

Personally, I think Python gets it right: by default, warnings are only
printed once each. Instead of getting a million

WARNING: 32x32 icon missing, using 16x16 icon

you only see it once.



-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

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


Re: The "loop and a half"

2017-10-07 Thread bartc

On 07/10/2017 02:46, Steve D'Aprano wrote:

On Sat, 7 Oct 2017 06:18 am, bartc wrote:


For sort, there is no real need. You use a text editor to create your
data. Then use existing file-based sort.


What you mean is, *you* see no need for sorting interactively, or sorting as
part of a pipeline of functions. That speaks more of your lack of imagination
and closed-mindedness than any real lack.


Where did I say that?

The 'existing file-based sort' works from files and pipes.

It's capturing the data to start with that it would be ludicrous to do 
interactively using such a crude interface.



Personally, if I have a few (say, a dozen or so) lines I want sorted, it is
much easier to:

- select text from whatever application I'm using;

- bring up a terminal (I almost always have one already open);

- type `sort ENTER`;

- middle-click to paste the lines;

- type Ctrl-D;

- select the output lines;

- paste back into the original application;



That's not entering the data interactively (such as typing 'sort' then 
it sits silently recording lines of text (you hope) until it sees EOF). 
You say the lines already exist in a text editor. Exactly what I said; 
you start with text that has already been entered or generated by other 
means.


However it does seem to expose a flaw in the ability of command line 
tools to work with non-command line tools.


So I have to copy 33,000 lines from a document, get to the terminal 
(keeping that document open because I'm not done with it), start 'sort', 
and paste those 33,000 lines into the console, then type Ctrl-D. Which 
then promptly prints the newly sorted 33,000 lines onto the console. 
Then you have to select those 33,000 lines (not easy as you now have 
find the midpoint of 66,000 lines of output), copy it, and paste it back 
into the app.


Put that way, it doesn't sound very sophisticated does it?

(Now I expect you're going to bombard with workarounds to fix all those 
issues.)



(seven steps)


versus:




That's not what I meant at all, which is about creating the data from 
scratch. Here, the data STILL already magically exists somewhere!


Is it possible that you guys have never had to create anything original?

(How would /I/ sort a block of text in my editor? There's no built-in 
function, so using your approach:


 * Select the block

 * Ctrl KWfileEnter to write it to 'file'

 * Elsewhere, sort file2

 * Back in editor, Ctrl KY Ctrl KRfile2Enter to delete then insert file2

Only four steps? Something went amiss in your analysis I think. And even 
these could be simplified by Using Ctrl KS and Ctrl KL to use a 
predefined clipboard-like filename for the intermediate.


However, how hard would it for the editor to do its own sorting? Not 
very, as it turns out, only half a dozen lines of code (see below after 
sig). Now the sequence is:


  * Select the block

  * Ctrl KH

How many steps did you have, seven?)


I forget... it is "work harder, not smarter"? Being inefficient is a good
thing, right?


Okay

--
bartc

--
proc cmd_ctrlkh <"med:*ck*ch "> (td) =
if td.blockstart then
isort(td.text[td.blockstart..td.blockend])
pageupdate(td)
fi
end
--
https://mail.python.org/mailman/listinfo/python-list


Re: The "loop and a half"

2017-10-07 Thread bartc

On 07/10/2017 03:18, Chris Angelico wrote:

On Sat, Oct 7, 2017 at 12:50 PM, Steve D'Aprano
 wrote:

On Sat, 7 Oct 2017 06:21 am, Chris Angelico wrote:


I'm not sure what printing to a window or image would mean, or how
it's useful, but sure.


Print to window: Print Preview.

Print to image: export to pdf or jpg or png.


Except that that isn't what you get in his programming language. What
you seem to get (judging from his response to the post you're quoting)
is something that lets you treat a GUI window as if it were a console,
printing text to it in some sort of "glass teletype" way. Leaves me
wondering if he's ever taken one of his apps to a system that uses a
different default font, or anything like that. Unless all his GUIs are
built in HTML?


(That particular language was one I was using over 20 years ago and it 
was an integrated part of a CAD application (and it started off 
pre-Windows).


The app also supported printer/plotter/image destinations including 
PostScript. The same language could take a marked-up text file, convert 
it to a series of drawing elements, then render and print that page on a 
PS printer. Then the same with the next page. I think I did a 350-page 
manual like that. With pictures.


My current language doesn't link its 'print' to graphic displays or images.)

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


Re: The "loop and a half"

2017-10-07 Thread bartc

On 07/10/2017 09:35, Steve D'Aprano wrote:

On Sat, 7 Oct 2017 11:05 am, bartc wrote:



Um, that actually follows what interactive Python does.



What is "that" to which you refer?

If you mean, "what I, Bart C, suggested, namely having the program exit on a
blank line", then you are wrong. In the Python interactive interpreter, you
can enter blank lines, and the interpreter doesn't exit.



There's one priviso: blank lines are only ignored at the primary prompt >>>
not the secondary prompt ... where a blank line is used to end the block. But
the interpreter doesn't exit. A slight compromise for the sake of convenience
at the interactive prompt.


That's what I mean. Enter is used to end one state and get back to another.

The same thing with my loop evaluating expressions. When you're done 
with with expressions, you might exit in the trivial example, or you 
might get back to a main command loop. Just like Python.





(Most of my real interactive programs with a command line interface
programs use Escape, quit, exit, q or x to finish.


And how do you distinguish between calling quit from inside the function, and
using quit inside the function?


Huh? Most interactive programs aren't language interpreters like Python, 
where everything needs to be considered to be a line in the language syntax.



Unfortunately ESCAPE is already used. VT100 (the terminal emulation which is
used in just about all terminals) all control sequences begin with ESC. So
every time you do something like press an arrow key, the terminal sends ESC
followed by other stuff. It would be painful if every time you hit an arrow
key, the interpreter took it as "Exit".


Yes, I discovered this. So my programs that use Escape on Windows needed 
to use Escape Escape on Linux to get around that.



Interactive Python requires quit() or exit(), complete with parentheses.
Unless you've redefined quit and exit as something else, then you have
to crash out by other means.)


"Crash out", he says.

If your intention is to prove that you're a know-nothing ignoramus, you're
doing an excellent job of it.


Yes, crash out. I've always considered control sequences as something 
out of the ordinary used when things go wrong. Eg:


 <<< while 1:
 <<< pass
 <<<

Here it appears to hang, and nothing you type does anything except (on 
Windows) Ctrl-C. That's what I call crashing out. Although that stays 
within the interpreter. If I press Ctrl-Break instead, it aborts the 
interpreter too.


What exactly is your problem, that anyone who has a different take on 
things must be an 'ignoramus'? And, to boot, an ignoramus who knows nothing?


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


Re: The "loop and a half"

2017-10-07 Thread Steve D'Aprano
On Sat, 7 Oct 2017 11:06 pm, bartc wrote:

> That's not entering the data interactively (such as typing 'sort' then
> it sits silently recording lines of text (you hope) until it sees EOF).

I manually hit paste, that's just as much a form of data entry as typing
characters one at a time. And then I hit Ctrl-D, and the program responds by
sorting the input. That's a manual, interactive process.

My example only specified copying data out of another application because
that's my usual use-case. Perhaps I'm writing an email, or using a news
reader (as I'm doing now).

But that part isn't critical. Perhaps I haven't typed them yet. Since there's
only a few of them, a dozen or so, its trivial to type or paste them into
stdin. Because I'm not a caveman, I use all the tools at my disposal, and
that includes the ability to copy and paste from one application to another.

Maybe I even type some lines, and paste others. Its 2017 and I've been using
computers long enough to know how to copy and paste from one application to
another like a Boss. You ought to see me, I drag the mouse over text like a
virtuoso, and middle-click like a world-champion.

The fact that stdin is a pretty feature-poor line based editor is neither in
dispute nor is it a problem. If I make a mistake, its no big deal. I just
re-type the line, sort the lot including the erroneous line, then edit out
the bad line after I've pasted it into the email.

YOU, not me, is the one talking in absolutes: according to you, nobody could
possibly need anything less than a full-featured user-friendly application
with prompts and all the bells and whistles in order to sort even half a
dozen lines of text. You make absolute statements about how we ought to work:

"You use a text editor to create your data. Then use existing 
file-based sort."

No we don't. Not always. Sometimes we might, but its not compulsory and
sometimes the task is small enough that having sort read from stdin is all we
need. There's no need for saving text into a file.

I've given you a real-world actual use-case where your solution is
inconvenient, complicated and difficult. This is a case where I don't need
all the bells and whistles you claim are indispensable.

I'm not saying there's "never" a use for such an application. Of course there
are cases where entering data into stdin is inconvenient and underpowered.
Nobody disputes that. YOU are arguing against some imaginary, exaggerated
position where we say that nobody ever, under any circumstances, needs a UI
more friendly than bare-bones stdin.

Nobody said that. You are projecting your own absolutism onto us. We're
explaining why the sort program is designed the way it is. That doesn't mean
that other designs don't have their uses too.


> You say the lines already exist in a text editor. 

I said "whatever application I'm using", which is not necessarily a text
editor. Perhaps it is my email client. Perhaps it is a graphics program, and
I want to enter some sorted text. Perhaps its a web form.

Or perhaps I haven't actually typed the lines yet.


> Exactly what I said; 
> you start with text that has already been entered or generated by other
> means.

Unless I don't.


> However it does seem to expose a flaw in the ability of command line
> tools to work with non-command line tools.
> 
> So I have to copy 33,000 lines from a document, 

Don't be daft. Nobody says that stdin is a sufficient interface for a
heavy-weight task like that. With 33000 lines of text, I absolutely would
save them to a permanent file on disk, because I wouldn't want to risk having
the application crash or the power go off just as I've typed line 32999 and
lose the lot.

For 33000 lines, having one extra temporary file floating around is a cost
worth paying. For 33 lines, it is not.

You want a one-size fits all solution. Are you capable of understanding that
different tasks and different scenarios are often best solved using different
techniques?


[...]
> Put that way, it doesn't sound very sophisticated does it?

Nobody said it was sophisticated. That's the whole point: having sort read
from stdin as you type into the terminal is the LEAST sophisticated,
simplest, most bare-bones, basic technique that works.

If I want to prise open the lid of a paint can, a screwdriver will do the job.
I don't need to purchase a $50 gold-plated electric paint lid opening machine
that requires ten minutes to set up. Now maybe if I needed to open 33000
paint tins, it would be worth using a more heavyweight solution. But I only
need to open two tins. A screwdriver is fine.


> (Now I expect you're going to bombard with workarounds to fix all those
> issues.)

Not at all. 



[...]
> 

You've got data in an email client. You've already typed it out, and then you
think "I want this sorted". What do you do?

You have to copy the lines into a text editor, save to disk, then launch your
file-based sort program, tell it to sort the saved file, reload the saved
file, copy th

Re: The "loop and a half"

2017-10-07 Thread bartc

On 07/10/2017 14:19, Steve D'Aprano wrote:

On Sat, 7 Oct 2017 11:06 pm, bartc wrote:



Ctrl-K to enter "operate on selected text" mode;
Y to Delete
Ctrl-K to enter "operate on selected text" mode;
R to Read from a file (at last an actual mnemonic command!)
enter a file name

That's five steps.


Are we counting steps or keystrokes?


And now you have two "temporary" files, file and file2, which need to be
deleted. Two more steps that you conveniently don't count.


Actually I keep a set of 9 scratch file names just for such purposes. So 
overwriting and deleting don't matter. (Apparently the names are 
offensive to some so I won't mention them, but they're easy to type.)



And you think that memorising these non-standard keyboard shortcuts Ctrl-KW
Ctrl-KY Ctrl-KR


I believe these used to be WordStar commands, if anyone can remember that.

 is better than memorising Ctrl-D which works across thousands

of applications? Good for you. You probably would love Emacs, except other
people use it, and therefore you will hate it.


[...]

However, how hard would it for the editor to do its own sorting?


Yes, it is a mystery to me why so few editors include a "sort lines" function.


I don't know if you're being sarcastic here or not, so I don't know if 
you mean few editors have 'sort' or most of them do. Neither do I get 
the point you're making.


But it's a little ironic that it took less time to add such a feature 
than I spent writing about it in a post!


--
bart

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


Re: callable values

2017-10-07 Thread Thomas Jollans
On 07/10/17 01:58, Steve D'Aprano wrote:
> On Sat, 7 Oct 2017 03:25 am, Stefan Ram wrote:
>
>>   FWIW, in my course notes, I have coined a special word for
>>   this:
>>
>>   A /prelate/ (German: "Prälat") is a callable value (object).
>
> In English, prelate is a kind of priest, a senior clergyman and dignitary.

... which is, of course, exactly what „Prälat“ means.

>
> I don't know whether German makes a practice of taking arbitrary verbs and
> adjectives and turning them into nouns, but English does, and so a callable
> object is just called a "callable".
>
>
>

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


python multiprocessing

2017-10-07 Thread Xristos Xristoou
I have three functions in the python that each one puts an image (image path) 
as input and makes a simple image processing and creates a new image (image 
path) as output.
in the example below, one function depends on the other, ie: the function of 
alg2 takes as input the image that generates the function of alg and the 
function of alg3 assign as input the image that generates the function of alg2 
which depends on the function of alg1.
(I hope you do not mind basically)
because of their relatively high execution time (image processing is that) I 
would like to ask if I can to parallelize them using python multiprocessing. I 
have read about multiprocessing map and pool but I was pretty confused .
whenever I summarize I have three interdependent functions and I would like to 
run them together if done. I would also like to know how I would perform these 
three functions in a contemporary way if they were not interdependent, ie each 
was autonomous.

def alg1(input_path_image,output_path_image):
start = timeit.default_timer()
###processing###)
stop = timeit.default_timer()
print stop - start
return output_path_image

def alg1(output_path_image,output_path_image1):
start = timeit.default_timer()
###processing###
stop = timeit.default_timer()
print stop - start
return output_path_image1

def alg3(output_path_image1,output_path_image2):
start = timeit.default_timer()
###processing###
stop = timeit.default_timer()
print stop - start
return output_path_image2

if __name__ == '__main__':
   alg1(output_path_image,output_path_image)
   alg2(output_path_image1,output_path_image1)
   alg3(output_path_image2,output_path_image2)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: The "loop and a half"

2017-10-07 Thread bartc

On 07/10/2017 14:19, Steve D'Aprano wrote:

On Sat, 7 Oct 2017 11:06 pm, bartc wrote:



So I have to copy 33,000 lines from a document,


Don't be daft. Nobody says that stdin is a sufficient interface for a
heavy-weight task like that. With 33000 lines of text, I absolutely would
save them to a permanent file on disk, because I wouldn't want to risk having
the application crash or the power go off just as I've typed line 32999 and
lose the lot.


You're missing something I think. The 33K lines already exist elsewhere, 
and have been copied to the clipboard. So you won't lose anything if the 
power goes off, assuming the original are secure.



For 33000 lines, having one extra temporary file floating around is a cost
worth paying. For 33 lines, it is not.


I was demonstrating the crudeness of copying and pasting to a console 
window rather than between proper applications. That was easier to show 
with a larger example which highlighted some of the practical aspects.



You want a one-size fits all solution. Are you capable of understanding that
different tasks and different scenarios are often best solved using different
techniques?


[...]

Put that way, it doesn't sound very sophisticated does it?


Nobody said it was sophisticated. That's the whole point: having sort read
from stdin as you type into the terminal is the LEAST sophisticated,
simplest, most bare-bones, basic technique that works.


You do remember this was about using programs /like/ sort as a model for 
writing true interactive scrolling text apps?


I said it was a poor model because sort is normally used with files and 
pipes. You're trying to keep it as a viable model because, sometimes, 
sort can also be used with pasted text which sort reads as as though it 
had been typed in real time (not from a pipe or file anyway).


OK, I'm not suggesting doing away with that.

But it is still a bad model of text application to use elsewhere, even 
if extra prompts were added. For one thing, it only reads one block of 
data, then it stops. A more typical text application will be doing 
different things requiring different entry modes.


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


Re: The "loop and a half"

2017-10-07 Thread Steve D'Aprano
On Sat, 7 Oct 2017 11:54 pm, bartc wrote:

> So my programs that use Escape on Windows needed
> to use Escape Escape on Linux to get around that.


Or you could just follow the expected Unix interface instead of inventing your
own.


Back in the days when I used a Mac (long before OS X), I used to hate it when
Windows developers would port their software to Mac. With the exception of a
few big software companies like Microsoft, who had actual Mac teams, they
would do what you do: completely ignore the Apple UI guidelines and port
their unfamiliar and arbitrary user interfaces to the Mac software, making it
essentially unusable.


-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

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


Re: The "loop and a half"

2017-10-07 Thread Grant Edwards
On 2017-10-07, bartc  wrote:

> Interactive Python requires quit() or exit(), complete with parentheses.

Nonsense.  On Unix you can just press ctrl-D (or whatever you have
configured as eof) at the command prompt. On windows, it's Ctrl-Z
.

> Unless you've redefined quit and exit as something else, then you have 
> to crash out by other means.)

Admit it, you're just trolling.

Plonk.


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


Re: Interactive scripts (back on topic for once) [was Re: The "loop and a half"]

2017-10-07 Thread Grant Edwards
On 2017-10-07, Steve D'Aprano  wrote:

> They're probably to busy re-doing working programs from scratch every
> few versions, with a brand new "improved" UI (almost invariably
> including a kool new design that uses light grey text on an ever so
> slightly lighter grey background)

Yes!  That!

> and deleting any useful functionality that the lead developer
> personally doesn't use, because "nobody uses that".
>
> https://www.jwz.org/doc/cadt.html

>From the above:

   "Why not be honest and resign yourself to the fact that version 0.8 is
followed by version 0.8, which is then followed by version 0.8?"

I think he's being overly optimistic.  If you want to be honest about
a lot of open-source GUI stuff, version 0.8 should generally be
followed by 0.7.

It seems that the state of affairs in non-GUI open source programs is
far, far better -- maintainers often actually care whether the program
works correclty and does useful things.

-- 
Grant



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


Re: The "loop and a half"

2017-10-07 Thread eryk sun
On Sat, Oct 7, 2017 at 1:06 PM, bartc  wrote:
>
> So I have to copy 33,000 lines from a document, get to the terminal (keeping
> that document open because I'm not done with it), start 'sort', and paste
> those 33,000 lines into the console, then type Ctrl-D. Which then promptly
> prints the newly sorted 33,000 lines onto the console. Then you have to
> select those 33,000 lines (not easy as you now have find the midpoint of
> 66,000 lines of output), copy it, and paste it back into the app.

Just redirect sort's output to the clipboard. In X11 a common program
for this is xclip, e.g. `sort | xclip`, which defaults to the
"primary" clipboard but can also use the "secondary" and "clipboard"
clipboards.

In Windows it's clip.exe, e.g. `sort /u /c | clip`, where /u and /c
are undocumented sort switches to use UTF-16 output and a
case-sensitive sort.

That said, I wouldn't use sort.exe to read input from the Windows
console since it uses the legacy codepage. Instead I'd use the new
Linux subsystem in Windows 10, which as of the Creators update
supports piping between Linux and Windows programs and reads Unicode
from the console. Run `bash` and then `sort | clip.exe`. Finish with
Ctrl+D, and Bob's your uncle. Using MSYS bash.exe and sort.exe (e.g.
from Git for Windows) is another option.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: The "loop and a half"

2017-10-07 Thread bartc

On 07/10/2017 15:45, Grant Edwards wrote:

On 2017-10-07, bartc  wrote:


Interactive Python requires quit() or exit(), complete with parentheses.


Nonsense.  On Unix you can just press ctrl-D (or whatever you have
configured as eof) at the command prompt. On windows, it's Ctrl-Z
.


Steve spoke about the 'usual quit/exit/bye' commands.

If you type 'quit' in interactive Python, then it says:

  Use quit() or Ctrl-Z plus Return to exit

Same for exit. So in Python, IF you want to use quit or exit to 
terminate, you have to use quit() or exit() instead.


So please explain how what I wrote was nonsense.


Unless you've redefined quit and exit as something else, then you have
to crash out by other means.)


Admit it, you're just trolling.


FFS, NOW what's wrong?

IF you DO redefine those names, then you DO have to use other means to 
terminate. I happen to call those means 'crashing out', because it's 
like yanking the plug rather than using the on/off switch. Especially on 
Windows where the usual Ctrl C doesn't work, so you resort to Ctrl-Break 
will which actually abort it. Ctrl Z is uncommon.


I suspect it's you trying to deliberately wind ME up.

I'm getting fed up with this thread now.


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


Re: The "loop and a half"

2017-10-07 Thread Steve D'Aprano
On Sun, 8 Oct 2017 12:49 am, bartc wrote:

> On 07/10/2017 14:19, Steve D'Aprano wrote:
>> On Sat, 7 Oct 2017 11:06 pm, bartc wrote:
> 
>> Ctrl-K to enter "operate on selected text" mode;
>> Y to Delete
>> Ctrl-K to enter "operate on selected text" mode;
>> R to Read from a file (at last an actual mnemonic command!)
>> enter a file name
>> 
>> That's five steps.
> 
> Are we counting steps or keystrokes?

Steps. If I was counting keystrokes, entering the filename "file" would have
counted as five. It didn't.


>> And now you have two "temporary" files, file and file2, which need to be
>> deleted. Two more steps that you conveniently don't count.
> 
> Actually I keep a set of 9 scratch file names just for such purposes.

So that's yet another thing for you to memorise rather than Ctrl-D for EOF.

Bart, its cool that you have your own personal, idiosyncratic way of working
that suits you. (I'm not being sarcastic.) If it works for you, great. Nobody
says you have to change your own personal workflow. You've got a bunch of
personal habits and customised tools that do just what you want them to do
and how YOU want them to do, and that's great for you. We accept that.

Please have the decency to return the favour.

Just because other people follow a different workflow and use tools that make
other choices than yours, doesn't make them wrong, and it doesn't make those
other tools substandard.

You're old enough and supposedly mature enough that you ought to know that
before you criticise a technical solution, you should at least try to
understand what problem it is solving before deciding it is wrong.


[...]
>> And you think that memorising these non-standard keyboard shortcuts Ctrl-KW
>> Ctrl-KY Ctrl-KR
> 
> I believe these used to be WordStar commands, if anyone can remember that.

Never used it, but I remember when WordPerfect for Mac came with a keyboard
overlay with WordStar commands on it.

But WordStar or not, you still have to memorise a bunch of commands to get a
task done, commands which don't work anywhere else. You're happy to do it,
which is great. Vim and Emacs users make the same choice, to memorise many
special, idiosyncratic ways of working in a text editor which don't apply
anywhere else. We don't judge: some people love Vim, some love Emacs, some
prefer lightweight GUI editors, some use heavy-duty IDEs.



>> [...]
>>> However, how hard would it for the editor to do its own sorting?
>> 
>> Yes, it is a mystery to me why so few editors include a "sort lines"
>> function.
> 
> I don't know if you're being sarcastic here or not, so I don't know if
> you mean few editors have 'sort' or most of them do. Neither do I get
> the point you're making.

I'm not being sarcastic, and I'm agreeing with you.

Sorting a few lines is not a hard task, and yet not one of my GUI editors have
it as either a built-in command or even a default plug-in. (There may be
third-party plugins I don't know of.)

I daresay that Emacs, at least, will have a sort command, but as they say
about Emacs, it would be the perfect operating system if only its standard
text editor wasn't so bad.

(Hey, just because I respect the right of people to choose Emacs, doesn't mean
I can't make fun of its size and bloatedness.)



-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

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


Re: The "loop and a half"

2017-10-07 Thread Chris Angelico
On Sun, Oct 8, 2017 at 2:06 AM, bartc  wrote:
> On 07/10/2017 15:45, Grant Edwards wrote:
>> Admit it, you're just trolling.
>
> FFS, NOW what's wrong?
>
> IF you DO redefine those names, then you DO have to use other means to
> terminate. I happen to call those means 'crashing out', because it's like
> yanking the plug rather than using the on/off switch. Especially on Windows
> where the usual Ctrl C doesn't work, so you resort to Ctrl-Break will which
> actually abort it. Ctrl Z is uncommon.
>
> I suspect it's you trying to deliberately wind ME up.
>
> I'm getting fed up with this thread now.

It's when you call that "crashing out" that people think you're just
trolling. Why on earth would that be a crash? Don't you know of any
other way to perform an orderly shutdown in a Python script? You talk
about Ctrl-C/Ctrl-Break as if it were an orderly shutdown, yet ignore
all of the other methods and call them "crashing".

Is there any surprise that people call you out for that?

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


Re: The "loop and a half"

2017-10-07 Thread Michael Torrie
On 10/06/2017 07:24 AM, bartc wrote:
> On 06/10/2017 14:11, Peter J. Holzer wrote:
>> I regularly use at least cat, wc and od this way (plus a few of my own
>> utilities like utf8dump). I'm sure I've used sort this way, too, though
>> rather rarely. I usually don't type the input but paste it in,
> 
> Exactly. Probably no one ever uses these programs with actual live input 
> with the possibility of uncorrectable errors getting through.

I regularly use cat in an interactive way. Most Unix users do.

cat >somefile.txt
sometext
^D

It's a very fast way of moving stuff from the clipboard to a file
without having to fire up an editor.

I'm not sure a prompt would benefit very much here, since this is such a
common operation once you learn it.

In MS-DOS to create a file you do "copy con: file" and then you also get
a blinking cursor with no prompt. Yet this was just something we did
with MS-DOS.  Not sure a prompt would have gained much.


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


Re: The "loop and a half"

2017-10-07 Thread Steve D'Aprano
On Sun, 8 Oct 2017 01:15 am, bartc wrote:

> On 07/10/2017 14:19, Steve D'Aprano wrote:
>> On Sat, 7 Oct 2017 11:06 pm, bartc wrote:
> 
>>> So I have to copy 33,000 lines from a document,
>> 
>> Don't be daft. Nobody says that stdin is a sufficient interface for a
>> heavy-weight task like that. With 33000 lines of text, I absolutely would
>> save them to a permanent file on disk, because I wouldn't want to risk
>> having the application crash or the power go off just as I've typed line
>> 32999 and lose the lot.
> 
> You're missing something I think. The 33K lines already exist elsewhere,
> and have been copied to the clipboard. So you won't lose anything if the
> power goes off, assuming the original are secure.

If I have the 33K lines in a file already, why would I copy them and paste
them into stdin (possibly overflowing the input buffer in the terminal) when
I can just call sort on the file?

I can even sort in place:

sort -o filename filename

You seem to have decided that it is our position that the one and only
acceptable way to use the sort command is to launch it with no options, then
laboriously type (or copy and paste) all the lines into stdin.

We're not idiots. We have many options, and we use the one which is most
appropriate for the task at hand.


>> [...]
>>> Put that way, it doesn't sound very sophisticated does it?
>> 
>> Nobody said it was sophisticated. That's the whole point: having sort read
>> from stdin as you type into the terminal is the LEAST sophisticated,
>> simplest, most bare-bones, basic technique that works.
> 
> You do remember this was about using programs /like/ sort as a model for
> writing true interactive scrolling text apps?

I don't remember any such thing. I remember you *claiming* that, but if anyone
actually did make that claim, I haven't seen it.

There are reasons why sort defaults to not providing a richer UI. Its not
intended as a "Sort Stuff App". It is designed to be used in Unix command
pipelines, where an introductory message would be a nuisance.

sort *could* detect when it is reading from stdin interactively and give an
introductory message. I already said this. The fact that it doesn't is a
matter of the personal taste of the author, who presumably doesn't think it
is necessary. Simplicity is itself a virtue, although not necessarily to
beginners.



-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

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


exception should not stop program.

2017-10-07 Thread Prabu T.S.
I would like to continue to second function invocation 
"checkServiceStatus('AdobeARMservice')" even if the first 
   checkServiceStatus('Tomcat9')  has any exception.Please advice.Second 
function invocation not getting executed if any exception occurs in 
first.Please advice.


import psutil

def checkServiceStatus(server):
status = None
try:
service = psutil.win_service_get(server)
status = service.as_dict()
print("%s (%s)" % (status['name'], status['display_name']))
print("status: %s, start: %s, username: %s, pid: %s" % (
status['status'], status['start_type'], status['username'], 
status['pid']))
print("binpath: %s" % status['binpath'])
print(" ")
except Exception:
pass
return status

checkServiceStatus('Tomcat9')
checkServiceStatus('AdobeARMservice')

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


Re: exception should not stop program.

2017-10-07 Thread Prabu T.S.
On Saturday, October 7, 2017 at 12:38:11 PM UTC-4, Prabu T.S. wrote:
> I would like to continue to second function invocation 
> "checkServiceStatus('AdobeARMservice')" even if the first 
>checkServiceStatus('Tomcat9')  has any exception.Please advice.Second 
> function invocation not getting executed if any exception occurs in 
> first.Please advice.
> 
> 
> import psutil
> 
> def checkServiceStatus(server):
> status = None
> try:
> service = psutil.win_service_get(server)
> status = service.as_dict()
> print("%s (%s)" % (status['name'], status['display_name']))
> print("status: %s, start: %s, username: %s, pid: %s" % (
> status['status'], status['start_type'], status['username'], 
> status['pid']))
> print("binpath: %s" % status['binpath'])
> print(" ")
> except Exception:
> pass
> return status
> 
> checkServiceStatus('Tomcat9')
> checkServiceStatus('AdobeARMservice')

ignore this for now.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: The "loop and a half"

2017-10-07 Thread Grant Edwards
On 2017-10-07, Steve D'Aprano  wrote:

> sort *could* detect when it is reading from stdin interactively and give an
> introductory message.

There are some command-line utilities that try to do that: they modify
their behavior when they think that stdin or stdout is connected to a
"terminal" instead of a pipe.  Personally, I find that annoying and
inconvenient.  I hate it when I run a program, look at the output and
decide I want to do some processing on it, so I hit 'ctrl-P' and pipe
the output to sed, grep, awk, sort, whatever.

And it doesn't work.


After wasting _way_ too much time trying to figure out what I did
wrong in my sed/grep/awk/whatever command, I finally realize that the
@#$!% program changes its output format when stdout is a pipe, and the
rest of the pipeline was designed to process the stdout-is-a-terminal
output format.

And don't get me started on command-line utilities that use colored
output that's only usable if yor terminal is configured with a black
background. Hint to gentoo portage authors: yellow-on-white text is
_not_ readable.

-- 
Grant






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


Re: exception should not stop program.

2017-10-07 Thread Jorge Gimeno
Catching all exceptions in a try-except block is almost always a bad idea.
You can't tell the difference between an exception that you are looking to
handle and an exception that should cause your program to crash and burn
(because something is wrong). It's best to catch a specific exception.
What condition are you looking to handle here?

-Jorge

On Sat, Oct 7, 2017 at 9:38 AM, Prabu T.S.  wrote:

> I would like to continue to second function invocation
> "checkServiceStatus('AdobeARMservice')" even if the first
>checkServiceStatus('Tomcat9')  has any exception.Please advice.Second
> function invocation not getting executed if any exception occurs in
> first.Please advice.
>
>
> import psutil
>
> def checkServiceStatus(server):
> status = None
> try:
> service = psutil.win_service_get(server)
> status = service.as_dict()
> print("%s (%s)" % (status['name'], status['display_name']))
> print("status: %s, start: %s, username: %s, pid: %s" % (
> status['status'], status['start_type'], status['username'],
> status['pid']))
> print("binpath: %s" % status['binpath'])
> print(" ")
> except Exception:
> pass
> return status
>
> checkServiceStatus('Tomcat9')
> checkServiceStatus('AdobeARMservice')
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Introducing the "for" loop

2017-10-07 Thread Terry Reedy

On 10/7/2017 5:09 AM, Steve D'Aprano wrote:

On Fri, 6 Oct 2017 11:44 pm, ROGER GRAYDON CHRISTMAN wrote:


Despite the documentation, I would still be tempted to say that range is a
function.
Taking duck-typing to the meta-level, every time I use range, I use its name
followed
by a pair of parentheses enclosing one to three parameters, and I get back
an
immutable sequence object.   It sure looks like a function to me.


I agree -- range() is a function in the (almost) mathematical sense, something
which takes arguments and returns a value. It's also a type (class), in the
OOP sense:


py> type(range)



The term "function" is ambiguous but normally clear from context. Often, the
differences make no difference, but when they are important, we can discuss
them:

- range is a callable (a callable object);

- it is also a type/class, and calling it returns an instance;

- it looks like, and behaves like, a function;

- and is, conceptually, a function;

- but it is *not* an instance of FunctionType:


py> from types import FunctionType
py> def function():
... pass
...
py> isinstance(function, FunctionType)
True
py> isinstance(range, FunctionType)
False


No built-in function is an instance of FunctionType
>>> isinstance(compile, FunctionType)
False
>>> isinstance(print, FunctionType)
False
>>> type(compile)

>>> type(int.bit_length)



FunctionType == function defined by def statement or lambda expression.
These are a subset of functions defined by Python code.


It is this last sense (an instance of FunctionType) which people are thinking
of when they state that range is not a function.


Unless one means 'function defined by def or class', excluding all 
functions defined in the interpreter implementation language, which can 
change as modules are recoded one way or the other, and some functions 
defined in Python, FunctionType is too narrow.  The predecate would have 
to be at least


BuiltinFunction = type(compile)
MethonDescriptor = type(int.bit_length)
isinstance(x, (FunctionType, BuiltinFunction, MethodDescriptor))

but that still excludes bound methods and partial functions.

I have the impression that classes being functions is somewhat peculiar 
to Python but I have not been exposed to enough OOP languages to know.


The other sense in which 'range is not a function' makes some sense is 
when it means 'range is not *just* a function'.  This is akin to when 
'people are not animals' means 'people are not (or should not be) *just* 
animals'.  Do people speaking other than English say subcategory Y of 
category X is special by saying 'Ys are not Xs'?


--
Terry Jan Reedy

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


Re: The "loop and a half"

2017-10-07 Thread bartc

On 07/10/2017 17:28, Steve D'Aprano wrote:

On Sun, 8 Oct 2017 01:15 am, bartc wrote:



You do remember this was about using programs /like/ sort as a model for
writing true interactive scrolling text apps?


I don't remember any such thing. I remember you *claiming* that, but if anyone
actually did make that claim, I haven't seen it.



bart:
> This doesn't make sense. For interactive use, you wouldn't bother
> testing for eof, as you'd be testing the eof status of the keyboard.
>

ChrisA:

> You mean the way heaps and heaps of Unix programs work, processing
> until EOF of stdin? Yeah, totally makes no sense, man, no sense at
> all.

bart:
> If you're referring to the ability to redirect stdin so that input can
> come from a file as well as from a live keyboard, then you're doing
> file handling; it's NOT interactive.

ChrisA:
> How would you write a sort program? How would you tell it that you're
> done entering data?

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


Re: The "loop and a half"

2017-10-07 Thread Terry Reedy

On 10/7/2017 10:45 AM, Grant Edwards wrote:

On 2017-10-07, bartc  wrote:


Interactive Python requires quit() or exit(), complete with parentheses.


Nonsense.  On Unix you can just press ctrl-D (or whatever you have
configured as eof) at the command prompt. On windows, it's Ctrl-Z
.


IDLE's shell quits on ^D at a prompt on all systems.  (This became true 
before I worked on IDLE.)

Clicking the [X] button should close any window on all systems.

--
Terry Jan Reedy

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


Re: exception should not stop program.

2017-10-07 Thread Grant Edwards
On 2017-10-07, Jorge Gimeno  wrote:

> Catching all exceptions in a try-except block is almost always a bad
> idea.

Catching it and ignoring it as the OP was doing (or assuming it's some
particular exception) certainly is.

If you know (or suspect) that stderr isn't going anywhere that it will
be seen, then catching all exceptions at the top of your program and
logging them and exiting with an error status is a reasonable thing to
do.

#!/usr/bin/python

import sys,syslog,traceback

def main():
[...]

try:
main()
except:
syslog.syslog("%s: %s\n" % (sys.argv[0], traceback.format_exc()))
sys.exit(1)

If it's a GUI program, then popping up an error dialog instead of
sending it to syslog might make more sense -- if you can be reasonably
sure that the GUI framework is still operational.

-- 
Grant Edwards   grant.b.edwardsYow! Am I accompanied by a
  at   PARENT or GUARDIAN?
  gmail.com

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


Re: exception should not stop program.

2017-10-07 Thread MRAB

On 2017-10-07 17:38, Prabu T.S. wrote:

I would like to continue to second function invocation 
"checkServiceStatus('AdobeARMservice')" even if the first
checkServiceStatus('Tomcat9')  has any exception.Please advice.Second 
function invocation not getting executed if any exception occurs in 
first.Please advice.


import psutil

def checkServiceStatus(server):
 status = None
 try:
 service = psutil.win_service_get(server)
 status = service.as_dict()
 print("%s (%s)" % (status['name'], status['display_name']))
 print("status: %s, start: %s, username: %s, pid: %s" % (
 status['status'], status['start_type'], status['username'], 
status['pid']))
 print("binpath: %s" % status['binpath'])
 print(" ")
 except Exception:
 pass
 return status

checkServiceStatus('Tomcat9')
checkServiceStatus('AdobeARMservice')

Catch the exception that's raised, like you're already doing in 
checkServiceStatus.

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


Re: Introducing the "for" loop

2017-10-07 Thread Chris Angelico
On Sun, Oct 8, 2017 at 3:58 AM, Terry Reedy  wrote:
> No built-in function is an instance of FunctionType
 isinstance(compile, FunctionType)
> False
 isinstance(print, FunctionType)
> False
 type(compile)
> 
 type(int.bit_length)
> 
>
>
> FunctionType == function defined by def statement or lambda expression.
> These are a subset of functions defined by Python code.
>
> Unless one means 'function defined by def or class', excluding all functions
> defined in the interpreter implementation language, which can change as
> modules are recoded one way or the other, and some functions defined in
> Python, FunctionType is too narrow.  The predecate would have to be at least
>
> BuiltinFunction = type(compile)
> MethonDescriptor = type(int.bit_length)
> isinstance(x, (FunctionType, BuiltinFunction, MethodDescriptor))
>
> but that still excludes bound methods and partial functions.

The three types lack a concrete base class... but fortunately, they
have an abstract one.

>>> isinstance(print, collections.abc.Callable)
True
>>> isinstance(int.bit_length, collections.abc.Callable)
True
>>> isinstance(lambda: 1, collections.abc.Callable)
True
>>> isinstance(range, collections.abc.Callable)
True

Now I know my ABCs. :)

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


Re: Creating a Dictionary

2017-10-07 Thread Pavol Lisy
On 10/5/17, Chris Angelico  wrote:
> On Thu, Oct 5, 2017 at 12:24 PM, Stefan Ram  wrote:
>>   One might wish to implement a small language with these commands:
>>
>> F - move forward
>> B - move backward
>> L - larger stepsize
>> S - smaller stepsize
>>
>>   . One could start with the following pseudocode for a dictionary:
>>
>> { 'F': lambda: myturtle.forward( s ),
>>   'B': lambda: myturtle.backward( s ),
>>   'L': lambda: global s; s *= 2,
>>   'S': lambda: global s; s /= 2 }
>>
>>   . But lambda-expressions cannot contain statements.
>>
>>   Any other suggestions?
>
> There are a few options here. One is to make use of a simple
> "collector decorator":
>
> commands = {}
> def cmd(f):
> commands[f.__name__.upper()] = f
> return f
>
> @cmd
> def f():
> myturtle.forward( s )
>
> @cmd
> def b():
> myturtle.backward( s )
>
> @cmd
> def l():
> global siz
> size *= 2
>
> @cmd
> def s():
> global siz
> size //= 2
>
> (Also untested, but the pattern is one I've used many times.)
>
> Another is to deploy the whole thing as a class, with no globals:
>
> class Turtle:
> def __init__(self):
> self.size = ...
> self.turtle = ...
> def cmd_F(self):
> self.turtle.forward(self.size)
> def cmd_B(self):
> self.turtle.backward(self.size)
> def cmd_L(self):
> self.size *= 2
> def cmd_S(self):
> self.size //= 2
>
> Note that I've added "cmd_" in front of the names, which means you can
> safely getattr(turtle, "cmd_" + letter) and be confident you won't
> accidentally grab something that isn't a command.
>
> (Note also that I used // for division. If your size is actually a
> float, then change those back to single slashes.)
>
> Either of these patterns would work fairly well. There are others,
> too, but I'd be inclined to use one of these.
>
> ChrisA
> --
> https://mail.python.org/mailman/listinfo/python-list

size = 2*size if size else 1
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Lies in education [was Re: The "loop and a half"]

2017-10-07 Thread Pavol Lisy
On 10/5/17, Steve D'Aprano  wrote:

> The A and E in the word "are" are not vowels, since they are silent.

Interesting! :)

Is then R (half?) silent in word "Brazil"?
-- 
https://mail.python.org/mailman/listinfo/python-list


Finding Old Posts on Python

2017-10-07 Thread Cai Gengyang
Hello,

Does anyone know of a way to find all my old posts about Python ? Thanks a lot!

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


Re: Lies in education [was Re: The "loop and a half"]

2017-10-07 Thread Richard Damon

On 10/4/17 11:22 PM, Steve D'Aprano wrote:

The A and E in the word "are" are not vowels, since they are silent.


The A is clearly not silent, unless you have some strange pronunciation. 
The fact that are is pronounced just like the NAME of the letter R 
doesn't mean it is silent.


Compare the sound of the word are (which begins like the 'pirate' phrase 
arrgh) to me, to a word that begins with a letter R like rat or ring. 
There is a clear aspiration in the former that isn't in the latter.


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


django project avoid reload page where work algorithm

2017-10-07 Thread Xristos Xristoou
I have a website where the user can be put three numbers on my html template 
and get some results from my personal mathematical algorithm. the result save 
at user personal table on my database and can see in specific tab in my website.
my problem is where the algorithm to calculate result maybe take time between 
5-10 minutes in this time the browser stay on reload. if user change tab or 
close browser or maybe have problem with internet connection then loose that 
request and need again to put the numbers and again wait for results.
I want after the user request from my form in html to keep this request and 
work my algorithm without reload the page and where the algorithm finish then 
to send the user some email or message or just need the user visit the tab of 
results to see new results.
that I want to avoid the problems where the algorithm is in running and user 
loose data or request or time.
is easy to do that using suproccess,celery or RabbitMQ ?
any idea ?
here the code
views.py
def math_alg(request):
if request.method == "POST":
test = request.POST.get('no1')
test = request.POST.get('no3')
test = request.POST.get('no3')
#start algorith
calc_math(no1,no1,no3,result)
instance = rmodel.objects.create(user=request.user,rfield=result)
instance.save
return render(request, 'page.html', {'result': result})
html :
{% csrf_token %}
  op math calculate:
  
  
  

  
{{result }}

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


Re: django project avoid reload page where work algorithm

2017-10-07 Thread MRAB

On 2017-10-08 01:40, Xristos Xristoou wrote:

I have a website where the user can be put three numbers on my html template 
and get some results from my personal mathematical algorithm. the result save 
at user personal table on my database and can see in specific tab in my website.
my problem is where the algorithm to calculate result maybe take time between 
5-10 minutes in this time the browser stay on reload. if user change tab or 
close browser or maybe have problem with internet connection then loose that 
request and need again to put the numbers and again wait for results.
I want after the user request from my form in html to keep this request and 
work my algorithm without reload the page and where the algorithm finish then 
to send the user some email or message or just need the user visit the tab of 
results to see new results.
that I want to avoid the problems where the algorithm is in running and user 
loose data or request or time.
is easy to do that using suproccess,celery or RabbitMQ ?
any idea ?

[snip]

You mentioned email, so why not just ask for an email address to which 
you will send the result?

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


"comprehend" into a single value

2017-10-07 Thread Andrew Z
Hello,
 i wonder how  can i accomplish the following as a one liner:

dict= {10: ['a',1,'c'], 20: ['d',2,'f']}
p = 0
for i in dict:
p += dict[i][1]


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


Re: Introducing the "for" loop

2017-10-07 Thread Steve D'Aprano
On Sun, 8 Oct 2017 03:58 am, Terry Reedy wrote:


> No built-in function is an instance of FunctionType
>  >>> isinstance(compile, FunctionType)
> False

Ah yes, thanks Terry, I forgot that builtin functions have a distinct type.


[...]
> FunctionType == function defined by def statement or lambda expression.
> These are a subset of functions defined by Python code.

Indeed.


>> It is this last sense (an instance of FunctionType) which people are
>> thinking of when they state that range is not a function.
> 
> Unless one means 'function defined by def or class', excluding all
> functions defined in the interpreter implementation language, which can
> change as modules are recoded one way or the other, and some functions
> defined in Python, FunctionType is too narrow.

Yes, I forgot about the other ways functions can be created, such as partial
objects and builtins and callable instances. (C++ calls them functors.)

However, people often distinguish between functions and methods, since methods
carry their own implicit state ("self") and traditionally functions don't.
But of course the line between them is blurred:

- closures (a kind of function) do carry implicit state;

- static methods in Python (a kind of method) don't carry implicit state.


[...]
> I have the impression that classes being functions is somewhat peculiar
> to Python but I have not been exposed to enough OOP languages to know.

Many languages use function call syntax MyClass(args) (or something quite
close to function call syntax) for instantiating a class. In the sense that a
function is defined by the use of function call syntax, then classes are
functions.

But in the sense that in some languages functions are values but classes are
not (e.g. Java), then classes should be considered distinct from functions.

As always, it depends on what you mean by function.



-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

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


Re: "comprehend" into a single value

2017-10-07 Thread Nathan Hilterbrand
dict= {10: ['a',1,'c'], 20: ['d',2,'f']}
p = sum([dict[i][1] for i in dict])

Something like that?

On Sat, Oct 7, 2017 at 11:07 PM, Andrew Z  wrote:

> Hello,
>  i wonder how  can i accomplish the following as a one liner:
>
> dict= {10: ['a',1,'c'], 20: ['d',2,'f']}
> p = 0
> for i in dict:
> p += dict[i][1]
>
>
> Thank you
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: "comprehend" into a single value

2017-10-07 Thread bob gailer

On 10/7/2017 11:17 PM, Nathan Hilterbrand wrote:

dict= {10: ['a',1,'c'], 20: ['d',2,'f']}
p = sum([dict[i][1] for i in dict])

Something like that?

Ah, but that's 2 lines.

sum(val[1] for val in  {10: ['a',1,'c'], 20: ['d',2,'f']}.values())

On Sat, Oct 7, 2017 at 11:07 PM, Andrew Z  wrote:


Hello,
  i wonder how  can i accomplish the following as a one liner:

dict= {10: ['a',1,'c'], 20: ['d',2,'f']}
p = 0
for i in dict:
 p += dict[i][1]


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



--
Image and video hosting by TinyPic
--
https://mail.python.org/mailman/listinfo/python-list


Re: "comprehend" into a single value

2017-10-07 Thread Andrew Z
Nathan, Bob - on the money. Thank you !

On Sat, Oct 7, 2017 at 11:30 PM, bob gailer  wrote:

> On 10/7/2017 11:17 PM, Nathan Hilterbrand wrote:
>
>> dict= {10: ['a',1,'c'], 20: ['d',2,'f']}
>> p = sum([dict[i][1] for i in dict])
>>
>> Something like that?
>>
> Ah, but that's 2 lines.
>
> sum(val[1] for val in  {10: ['a',1,'c'], 20: ['d',2,'f']}.values())
>
> On Sat, Oct 7, 2017 at 11:07 PM, Andrew Z  wrote:
>>
>> Hello,
>>>   i wonder how  can i accomplish the following as a one liner:
>>>
>>> dict= {10: ['a',1,'c'], 20: ['d',2,'f']}
>>> p = 0
>>> for i in dict:
>>>  p += dict[i][1]
>>>
>>>
>>> Thank you
>>> --
>>> https://mail.python.org/mailman/listinfo/python-list
>>>
>>>
> --
> Image and video hosting by TinyPic
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: "comprehend" into a single value

2017-10-07 Thread Andrew Z
and how about adding "IF" into the mix ?

as in :

a=0

dict= {10: ['a',1,'c'], 20: ['d',2,'f']}

for i in dict:

 p+= 10 if dict[i][1] in [1,2,3,4,5] else 0


can i "squish" "for" and "if" together ? or will it be too perl-ish ?





On Sun, Oct 8, 2017 at 12:37 AM, Andrew Z  wrote:

> Nathan, Bob - on the money. Thank you !
>
> On Sat, Oct 7, 2017 at 11:30 PM, bob gailer  wrote:
>
>> On 10/7/2017 11:17 PM, Nathan Hilterbrand wrote:
>>
>>> dict= {10: ['a',1,'c'], 20: ['d',2,'f']}
>>> p = sum([dict[i][1] for i in dict])
>>>
>>> Something like that?
>>>
>> Ah, but that's 2 lines.
>>
>> sum(val[1] for val in  {10: ['a',1,'c'], 20: ['d',2,'f']}.values())
>>
>> On Sat, Oct 7, 2017 at 11:07 PM, Andrew Z  wrote:
>>>
>>> Hello,
   i wonder how  can i accomplish the following as a one liner:

 dict= {10: ['a',1,'c'], 20: ['d',2,'f']}
 p = 0
 for i in dict:
  p += dict[i][1]


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


>> --
>> Image and video hosting by TinyPic
>>
>
>
-- 
https://mail.python.org/mailman/listinfo/python-list