Re: tkinter MP working like a charm

2017-12-30 Thread Chris Angelico
On Sun, Dec 31, 2017 at 4:02 PM, Abdur-Rahmaan Janhangeer
 wrote:
> for beginners import * is probably fine. Even if you are using most modules
> then too. else if module small maybe ok too
>
> just when you import just what you need, you save on resources .
>

Actually no; the entire module still gets executed and loaded into
memory. It's just about how you name things.

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


Re: How to exec a string which has an embedded '\n'?

2017-12-30 Thread Random832
On Sat, Dec 30, 2017, at 23:57, jf...@ms4.hinet.net wrote:
> I have a multiline string, something like '''...\nf.write('\n')\n...'''
> when pass to exec(), I got
> SyntaxError: EOL while scanning string literal
> 
> How to get rid of it?

Use \\n for this case, since you want the \n to be interpreted by the exec 
parser rather than the newline being part of the string.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: tkinter MP working like a charm

2017-12-30 Thread Abdur-Rahmaan Janhangeer
for beginners import * is probably fine. Even if you are using most modules
then too. else if module small maybe ok too

just when you import just what you need, you save on resources .

Abdur-Rahmaan Janhangeer,
Mauritius
abdurrahmaanjanhangeer.wordpress.com

On 31 Dec 2017 05:00, "Wu Xi"  wrote:

> from tkinter import *#I cant see
> anything wrong with this , it works like a charm
> from tkinter import messagebox   #is there a
> serious concern doing things his way ?
> import asyncio , threading ,  random #goal is
> multi tasking with the GUI not freezing before loop completed
>  #which is
> being achieved here !
> def _asyncio_thread(async_loop):
> async_loop.run_until_complete(do_urls())
>
> def do_work(async_loop):
> """ Button-Event-Handler starting stuff """
> threading.Thread(target=_asyncio_thread, args=(async_loop,)).start()
>
> async def one_url(url):
> """ One task. """
> sec = random.randint(1, 8)
> await asyncio.sleep(sec  )
> return 'url: {}  ---  sec: {}'.format(url, sec)
>
> async def do_urls():
> """ Creating and starting 10 tasks. """
> tasks   = [one_url(url)  for url  in range(10)]
> completed, pending =  await asyncio.wait(tasks)
> results = [task.result() for task in completed]
> print('\n'.join(results))
>
>
> def do_nofreeze():
> messagebox.showinfo(message='see, Tkinter is still responsive')
>
> def submain(async_loop):
> root = Tk()
> b1 = Button(master=root, text='do work',   command=
> lambda:do_work( async_loop)).pack()
> b2 = Button(master=root, text='Frozen?',   command=do_nofreeze
>  ).pack()
> root.mainloop()
>
>
> if __name__ == '__main__':
> async_loop = asyncio.get_event_loop()#  all in this loop
> submain(async_loop)
>
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: a nice editor in 100 lines

2017-12-30 Thread Abdur-Rahmaan Janhangeer
great ! maybe the next step is a syntax coloriser ^^_

Abdur-Rahmaan Janhangeer,
Mauritius
abdurrahmaanjanhangeer.wordpress.com

On 31 Dec 2017 02:05, "Wu Xi"  wrote:

> class writerKl(object):
> def __init__(self):
> import  tkinter
> fromtkinter import messagebox
> fromtkinter import filedialog
> fromtkinter import Tk
> fromtkinter import Menu
> fromtkinter import END
>
> self.fileName = None
> self.saved= True
> self.app  = tkinter.Tk()
> self.app.title("FenInst is another instance of the writerKl
> class")
>
> self.menuBar  = tkinter.Menu(self.app)
> self.fileMenu = tkinter.Menu(self.menuBar, tearoff=0)
> self.fileMenu.add_command(label="New",
>  command=self.newFile)
> self.fileMenu.add_command(label="Open",
> command=self.openFile)
> self.fileMenu.add_command(label="Save",
> command=self.saveFile)
> self.fileMenu.add_command(label="Save As",
> command=self.saveFileAs)
> self.fileMenu.add_separator() ;  self.About = "A selfish
> tkinter text editor in 100 lines of python3 code.\n\n In fact this very
> ''About window'' also was modded using the selfish editor himself.\n\n Open
> the source ''writer.py'' to find out why this editor is seen as so 105x
> self-obsessed."
> self.fileMenu.add_command(label= "About", command=lambda:
> tkinter.messagebox.showinfo("About", self.About))
> self.fileMenu.add_separator()
> self.fileMenu.add_command(label="Exit", command=self.onExit)
> self.menuBar.add_cascade( label="File", menu   =self.fileMenu)
> self.app.config(menu=self.menuBar)
>
> self.app.bind('', self.newFile )   # key
> Bindings
> self.app.bind('', self.openFile)
> self.app.bind('', self.saveFile)
> self.app.bind('',   self.setsavedFalse )
> self.app.protocol("WM_DELETE_WINDOW", self.onExit)# save
> before exit?
>
> self.textf  = tkinter.Text(self.app)  #
> initializing text container
> self.textf.pack(expand=True, fill='both') #
> deploying text container
> self.textf.focus()
> self.app.mainloop()
>
> def newFile(self):
> import  tkinter
> if not self.saved:
> save = self.promptToSave()
> if save:   self.saveFile()
> elif self.save is None:return
> self.fileName = None
> self.textf.delete(0.0, tkinter.END)
> self.saved = True
>
> def openFile(self):
> import  tkinter
> if not self.saved:
> self.save = self.promptToSave()
> if self.save:
> self.saveFile()
> elif self.save is None:
> return
> try:
> self.f = tkinter.filedialog.askopenfile( filetypes=[  ('all
> files', '*') , ('py files', '.py')  ] )
> if self.f:
> self.fileName = self.f.name
> self.t = self.f.read()
> self.textf.delete(0.0, tkinter.END)
> self.textf.insert(tkinter.END, self.t)
> self.saved = True
> except: tkinter.messagebox.showerror("Error", "Unable to
> open file.")
>
> def saveFile(self):
> import  tkinter
> self.t = self.textf.get(0.0, tkinter.END)
> if  self.fileName:
> self.f = open(self.fileName, "w")
> self.f.write(self.t)
> self.f.close()
> self.saved = True
> else:self.saveFileAs()
>
> def saveFileAs(self):
> import  tkinter
> self.f = tkinter.filedialog.asksaveasfile(defaultextension=".txt",
> filetypes=[ ('all files', '*'),('py files', '.py')  ])
> self.t = self.textf.get(0.0, tkinter.END)
> if self.f:
> try:
> self.f.write(self.t)
> self.f.close(  )
> self.saved = True
> self.fileName=self.f.name
> except: tkinter.messagebox.showwarning("Error", "Unable to
> save file.")
>
> def onExit(self):
> import  tkinter
> if notself.saved:
> self.save =   self.promptToSave()
> if self.save: self.saveFile()
> elif self.save is None:return
> self.app.destroy()
>
> def setsavedFalse(self, key):
> import  tkinter
> if (key.keysym.isalpha() or key.keysym.isdigit() or key.keysym in
> ["Return", "Tab", "Backspace", "Delete"]):   self.saved = False  # any key
> that changes text
>
> def promptToSave(self):
> import  tkinter
> return tkinter.messagebox.askyesnocancel( "Save file?", "Do
> you want to save the current file?")
>
>
> if __name__ == '__main__'

How to exec a string which has an embedded '\n'?

2017-12-30 Thread jfong
I have a multiline string, something like '''...\nf.write('\n')\n...'''
when pass to exec(), I got
SyntaxError: EOL while scanning string literal

How to get rid of it?

Best Regards,
Jach Fong
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Goto (Posting On Python-List Prohibited)

2017-12-30 Thread Ben Bacarisse
bartc  writes:

> On 30/12/2017 20:36, Ben Bacarisse wrote:
>> bartc  writes:
>>
>>> On 30/12/2017 16:53, mm0fmf wrote:
 On 30/12/2017 14:41, bartc wrote:
> it looks a bit naff

 Understatement of 2017.
>>>
>>> I'm honest about my own ideas, but my remarks were about the use of
>>> special symbols such as "::" and "@".
>>>
>>> Before completely dismissing it however, you should look at how
>>> another language such as Python can achieve the same thing.
>>>
>>> Namely, take any block of code within a function, and allow it to be
>>> executed or shared from anywhere else in the function, with the
>>> minimum of disruption.
>>
>> That's what a local function does and it does it with the clean
>> semantics of a function call.
>>
>> When this idea came up in comp.lang.c you could not see the point, yet
>> you appear to have a use-case common enough that you have a solution
>> worked out using gotos.
>
> C doesn't in general have local functions. My own languages don't
> implement them properly. So I tend not to use them.

But now you have good reason to change that.  Properly implemented they
do exactly what you want very neatly.  You can stick with gotos, of
course, but at least I hope you won't pour scorn on the idea of local
function if it comes up again.

>>> If it looks better than what I'd come up with, then I'll use that instead.
>>
>> What looks better is always going to be an unreliable and subjective
>> measure, but calling a named function almost certainly scales better and
>> will allow for better structuring (such as when one block needs to use
>> another one).
>
> Using a local (or even non-local) function is what I'm trying to
> avoid, as I prefer to keep the code inline, and not disrupt it too
> much.

That's what used to be called hacking.  You write it one way and then
spot that that block over there can be used here, but you don't tidy up
the code, you just jump to it!  In general, it is exactly the sort of
goto use that gave gotos a bad name.  Anyway, by their very nature, the
blocks you are talking about should not be inline since they don't
belong to any one execution path.


(I hope you don't mind this annotation -- over at comp.lang.c I just
remove text from my replies to you as is your preference, but people
here will not have seen that exchange and I prefer to mark edits.)

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


tkinter MP working like a charm

2017-12-30 Thread Wu Xi
from tkinter import *#I cant see 
anything wrong with this , it works like a charm
from tkinter import messagebox   #is there a 
serious concern doing things his way ? 
import asyncio , threading ,  random #goal is multi 
tasking with the GUI not freezing before loop completed
 #which is being 
achieved here !  
def _asyncio_thread(async_loop):
async_loop.run_until_complete(do_urls())

def do_work(async_loop):
""" Button-Event-Handler starting stuff """
threading.Thread(target=_asyncio_thread, args=(async_loop,)).start()

async def one_url(url):
""" One task. """
sec = random.randint(1, 8)
await asyncio.sleep(sec  )
return 'url: {}  ---  sec: {}'.format(url, sec)

async def do_urls():
""" Creating and starting 10 tasks. """
tasks   = [one_url(url)  for url  in range(10)]
completed, pending =  await asyncio.wait(tasks)
results = [task.result() for task in completed]
print('\n'.join(results))


def do_nofreeze():
messagebox.showinfo(message='see, Tkinter is still responsive')

def submain(async_loop):
root = Tk()
b1 = Button(master=root, text='do work',   command= lambda:do_work( 
async_loop)).pack()
b2 = Button(master=root, text='Frozen?',   command=do_nofreeze  
   ).pack()
root.mainloop()


if __name__ == '__main__':
async_loop = asyncio.get_event_loop()#  all in this loop
submain(async_loop)

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


Re: Goto (Posting On Python-List Prohibited)

2017-12-30 Thread MRAB

On 2017-12-30 23:22, Gregory Ewing wrote:

Stefan Ram wrote:

  BASIC has

DEF FN...

  which /can/ define actual subroutines, limited to expressions.

  Now, what does this limitation remind me of?


The equivalent limitation in Python is nowhere near as bad,
since if you outgrow what lambda can do you can always
use a def instead. BASIC didn't have that option (unless
you were using one of the more advanced dialects, such
as BBC BASIC, which had a PROC statement).

PROC wasn't really a statement, but a prefix for a procedure name. There 
was also another prefix, FN, for functions.


DEF PROChello
print "Hello world!"
ENDPROC

DEF FNsquare(x)
= x * x

They even had LOCAL variables and parameter lists. The Acorn Archimedes 
range had an improved version of BBC BASIC.

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


Re: Goto (Posting On Python-List Prohibited)

2017-12-30 Thread Chris Angelico
On Sun, Dec 31, 2017 at 10:45 AM, bartc  wrote:
> On 30/12/2017 23:26, Gregory Ewing wrote:
>>
>> bartc wrote:
>>>
>>> B and C occur twice, so a goto is a quick way to reuse B and C without
>>> needing to duplicate code,
>>
>>
>> This only works if the repeated part happens to be at the
>> tail of each case.
>
>
> IME that seems to be the most common situation.
>

I've written code that uses dirty tricks like that to avoid
duplication. It's at least as much of a problem as actual duplication
is. Generally, the 'goto' solution results in subsequent programmers
(such as my future selves) staring at the code for 30-60 seconds to
figure out what it's doing. I don't like to do that to myself, much
less to people I actually admire and respect.

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


Re: Python: asyncio and Tkinter

2017-12-30 Thread Wu Xi
this is kinda interesting. seems there is no easy way though
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Goto (Posting On Python-List Prohibited)

2017-12-30 Thread bartc

On 30/12/2017 23:26, Gregory Ewing wrote:

bartc wrote:
B and C occur twice, so a goto is a quick way to reuse B and C without 
needing to duplicate code,


This only works if the repeated part happens to be at the
tail of each case.


IME that seems to be the most common situation.

 Any other situation and you're back to

local functions.



--
Bartc

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


Re: Goto (Posting On Python-List Prohibited)

2017-12-30 Thread Gregory Ewing

bartc wrote:
B and C occur twice, so a goto is a quick way to reuse B and C without 
needing to duplicate code,


This only works if the repeated part happens to be at the
tail of each case. Any other situation and you're back to
local functions.

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


Re: Goto (Posting On Python-List Prohibited)

2017-12-30 Thread Gregory Ewing

bartc wrote:
C doesn't in general have local functions. My own languages don't 
implement them properly. So I tend not to use them.


Looks like there's something circular going on here. You don't
have much experience of using local functions, so you don't
see a lot of value in them, so you haven't made the effort to
implement them in your own languages, so you don't get much
experience in using them.

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


Re: Goto (Posting On Python-List Prohibited)

2017-12-30 Thread Gregory Ewing

Stefan Ram wrote:

  BASIC has

DEF FN...

  which /can/ define actual subroutines, limited to expressions.

  Now, what does this limitation remind me of?


The equivalent limitation in Python is nowhere near as bad,
since if you outgrow what lambda can do you can always
use a def instead. BASIC didn't have that option (unless
you were using one of the more advanced dialects, such
as BBC BASIC, which had a PROC statement).

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


Re: Goto (Posting On Python-List Prohibited)

2017-12-30 Thread Chris Angelico
On Sun, Dec 31, 2017 at 9:43 AM, bartc  wrote:
> On 30/12/2017 20:36, Ben Bacarisse wrote:
>>
>> bartc  writes:
>>
>>> On 30/12/2017 16:53, mm0fmf wrote:

 On 30/12/2017 14:41, bartc wrote:
>
> it looks a bit naff


 Understatement of 2017.
>>>
>>>
>>> I'm honest about my own ideas, but my remarks were about the use of
>>> special symbols such as "::" and "@".
>>>
>>> Before completely dismissing it however, you should look at how
>>> another language such as Python can achieve the same thing.
>>>
>>> Namely, take any block of code within a function, and allow it to be
>>> executed or shared from anywhere else in the function, with the
>>> minimum of disruption.
>>
>>
>> That's what a local function does and it does it with the clean
>> semantics of a function call.
>>
>> When this idea came up in comp.lang.c you could not see the point, yet
>> you appear to have a use-case common enough that you have a solution
>> worked out using gotos.
>
>
> C doesn't in general have local functions. My own languages don't implement
> them properly. So I tend not to use them.
>
>>> If it looks better than what I'd come up with, then I'll use that
>>> instead.
>>
>>
>> What looks better is always going to be an unreliable and subjective
>> measure, but calling a named function almost certainly scales better and
>> will allow for better structuring (such as when one block needs to use
>> another one).
>
>
> Using a local (or even non-local) function is what I'm trying to avoid, as I
> prefer to keep the code inline, and not disrupt it too much.
>
> You may also want to execute a block only temporarily, or as part of a short
> test. So you don't want to go to the trouble of hoisting a block of code
> into a local function.
>
> (And in C, which has local block scopes, there would be trouble with
> visibility of all the variables the block uses, unless the local function is
> untidily placed right where the original block was.)
>

Okay, so a low level language lacks certain facilities. Great. What
has this to do with Python and goto? You *can* use nested functions.
And they can do everything you need of these sub-blocks (albeit with
some overhead).

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


Re: Goto (Posting On Python-List Prohibited)

2017-12-30 Thread bartc

On 30/12/2017 20:36, Ben Bacarisse wrote:

bartc  writes:


On 30/12/2017 16:53, mm0fmf wrote:

On 30/12/2017 14:41, bartc wrote:

it looks a bit naff


Understatement of 2017.


I'm honest about my own ideas, but my remarks were about the use of
special symbols such as "::" and "@".

Before completely dismissing it however, you should look at how
another language such as Python can achieve the same thing.

Namely, take any block of code within a function, and allow it to be
executed or shared from anywhere else in the function, with the
minimum of disruption.


That's what a local function does and it does it with the clean
semantics of a function call.

When this idea came up in comp.lang.c you could not see the point, yet
you appear to have a use-case common enough that you have a solution
worked out using gotos.


C doesn't in general have local functions. My own languages don't 
implement them properly. So I tend not to use them.



If it looks better than what I'd come up with, then I'll use that instead.


What looks better is always going to be an unreliable and subjective
measure, but calling a named function almost certainly scales better and
will allow for better structuring (such as when one block needs to use
another one).


Using a local (or even non-local) function is what I'm trying to avoid, 
as I prefer to keep the code inline, and not disrupt it too much.


You may also want to execute a block only temporarily, or as part of a 
short test. So you don't want to go to the trouble of hoisting a block 
of code into a local function.


(And in C, which has local block scopes, there would be trouble with 
visibility of all the variables the block uses, unless the local 
function is untidily placed right where the original block was.)


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


Re: Tkinter,show pictures from the list of files in catalog-problem

2017-12-30 Thread Wu Xi
nothing works in ure soft


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


Re: Anaconda Navigator : Add App

2017-12-30 Thread Wu Xi
that is a very slow manager. too slow.
-- 
https://mail.python.org/mailman/listinfo/python-list


a nice editor in 100 lines

2017-12-30 Thread Wu Xi
class writerKl(object):
def __init__(self):  
import  tkinter
fromtkinter import messagebox 
fromtkinter import filedialog 
fromtkinter import Tk 
fromtkinter import Menu   
fromtkinter import END 

self.fileName = None  
self.saved= True
self.app  = tkinter.Tk() 
self.app.title("FenInst is another instance of the writerKl class") 


self.menuBar  = tkinter.Menu(self.app)
self.fileMenu = tkinter.Menu(self.menuBar, tearoff=0)
self.fileMenu.add_command(label="New", command=self.newFile)
self.fileMenu.add_command(label="Open",command=self.openFile)
self.fileMenu.add_command(label="Save",command=self.saveFile)
self.fileMenu.add_command(label="Save As", command=self.saveFileAs)
self.fileMenu.add_separator() ;  self.About = "A selfish tkinter 
text editor in 100 lines of python3 code.\n\n In fact this very ''About 
window'' also was modded using the selfish editor himself.\n\n Open the source 
''writer.py'' to find out why this editor is seen as so 105x self-obsessed."
self.fileMenu.add_command(label= "About", command=lambda: 
tkinter.messagebox.showinfo("About", self.About))
self.fileMenu.add_separator()
self.fileMenu.add_command(label="Exit", command=self.onExit)
self.menuBar.add_cascade( label="File", menu   =self.fileMenu)
self.app.config(menu=self.menuBar)

self.app.bind('', self.newFile )   # key Bindings
self.app.bind('', self.openFile)
self.app.bind('', self.saveFile)
self.app.bind('',   self.setsavedFalse )
self.app.protocol("WM_DELETE_WINDOW", self.onExit)# save before 
exit?

self.textf  = tkinter.Text(self.app)  # 
initializing text container
self.textf.pack(expand=True, fill='both') # deploying 
text container
self.textf.focus() 
self.app.mainloop()

def newFile(self):
import  tkinter
if not self.saved:
save = self.promptToSave()
if save:   self.saveFile()
elif self.save is None:return
self.fileName = None
self.textf.delete(0.0, tkinter.END)
self.saved = True

def openFile(self):
import  tkinter
if not self.saved:
self.save = self.promptToSave()
if self.save:
self.saveFile()
elif self.save is None:
return
try:
self.f = tkinter.filedialog.askopenfile( filetypes=[  ('all files', 
'*') , ('py files', '.py')  ] )
if self.f:
self.fileName = self.f.name
self.t = self.f.read()
self.textf.delete(0.0, tkinter.END)
self.textf.insert(tkinter.END, self.t)
self.saved = True
except: tkinter.messagebox.showerror("Error", "Unable to open 
file.")

def saveFile(self):
import  tkinter
self.t = self.textf.get(0.0, tkinter.END)
if  self.fileName:
self.f = open(self.fileName, "w")
self.f.write(self.t)
self.f.close()
self.saved = True
else:self.saveFileAs()

def saveFileAs(self): 
import  tkinter
self.f = tkinter.filedialog.asksaveasfile(defaultextension=".txt", 
filetypes=[ ('all files', '*'),('py files', '.py')  ])
self.t = self.textf.get(0.0, tkinter.END)
if self.f:
try:
self.f.write(self.t)
self.f.close(  )
self.saved = True
self.fileName=self.f.name
except: tkinter.messagebox.showwarning("Error", "Unable to save 
file.")

def onExit(self):
import  tkinter
if notself.saved:
self.save =   self.promptToSave()
if self.save: self.saveFile()
elif self.save is None:return
self.app.destroy()

def setsavedFalse(self, key):
import  tkinter
if (key.keysym.isalpha() or key.keysym.isdigit() or key.keysym in 
["Return", "Tab", "Backspace", "Delete"]):   self.saved = False  # any key that 
changes text

def promptToSave(self):
import  tkinter
return tkinter.messagebox.askyesnocancel( "Save file?", "Do you 
want to save the current file?")


if __name__ == '__main__' : 
import tkinter
FenInst  =writerKl() 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Goto (Posting On Python-List Prohibited)

2017-12-30 Thread William Ray Wing

> On Dec 30, 2017, at 7:46 AM, Peter J. Holzer  wrote:
> 
> On 2017-12-29 19:09:35 -0500, Dennis Lee Bieber wrote:
>> On Fri, 29 Dec 2017 23:12:22 +, bartc  declaimed the
>> following:
>>> Looking at 14 million lines of Linux kernel sources, which are in C, 
>>> over 100,000 of them use 'goto'. About one every 120 lines.
>>> 
>> 
>>  C is a language that predates the "structured programming" concepts of
>> the late 70/early 80.
> 
> I don't think this is correct. Structured programming is much older:
> ALGOL 60 was already a block structured language and Dijkstra wrote
> "goto considered harmful" in the late 1960s. Pascal appeared in 1970, C
> in 1974. To me (who learned to program in BASIC on a CP/M machine), C
> is very much a structured programming language. If structured
> programming gained traction around 1980, it might even have been because
> structured languages like C with good performance became widely
> available.
> 
> That said, C lacks exception handling (well, there is setjmp/longjmp,
> but ...) and multi-level break/continue, so goto is often the cleanest
> way to abort what you are doing and start to clean up. Python has
> exception handling, and that removes most of the cases where you would
> use goto in C (the rest is probably mostly in micro-optimizations: If
> you care about the run-time difference between a goto and a subroutine
> call, you probably shouldn't use Python in the first place).
> 
>hp
> 

I’ve been watching this discussion ebb and flow - and finally can’t resist 
pointing folks here at the famous essay: “Real Programmers Don’t Use Pascal”.  
It has its own Wikipedia article at this point:

 https://en.wikipedia.org/wiki/Real_Programmers_Don't_Use_Pascal

A copy of the original essay appears here: 
https://www.ee.ryerson.ca/~elf/hack/realmen.html

Hopefully fun reading over a beer.

Bill


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


Re: Goto (Posting On Python-List Prohibited)

2017-12-30 Thread Chris Angelico
On Sun, Dec 31, 2017 at 7:36 AM, Ben Bacarisse  wrote:
> bartc  writes:
>
>> On 30/12/2017 16:53, mm0fmf wrote:
>>> On 30/12/2017 14:41, bartc wrote:
 it looks a bit naff
>>>
>>> Understatement of 2017.
>>
>> I'm honest about my own ideas, but my remarks were about the use of
>> special symbols such as "::" and "@".
>>
>> Before completely dismissing it however, you should look at how
>> another language such as Python can achieve the same thing.
>>
>> Namely, take any block of code within a function, and allow it to be
>> executed or shared from anywhere else in the function, with the
>> minimum of disruption.
>
> That's what a local function does and it does it with the clean
> semantics of a function call.
>

The only downside that I can think of is performance - function calls
can be a bit heavy-weight. I'd be curious to see what a "lightweight
local function" would look like - it could have restrictive semantics
like "can only be called from the function that constructed it" and
then could behave like Bart's proposed "block of code". But I suspect
it wouldn't have all that many uses, compared to a *real* closure,
which can be passed around as its own entity.

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


Re: Goto (Posting On Python-List Prohibited)

2017-12-30 Thread Ben Bacarisse
bartc  writes:

> On 30/12/2017 16:53, mm0fmf wrote:
>> On 30/12/2017 14:41, bartc wrote:
>>> it looks a bit naff
>>
>> Understatement of 2017.
>
> I'm honest about my own ideas, but my remarks were about the use of
> special symbols such as "::" and "@".
>
> Before completely dismissing it however, you should look at how
> another language such as Python can achieve the same thing.
>
> Namely, take any block of code within a function, and allow it to be
> executed or shared from anywhere else in the function, with the
> minimum of disruption.

That's what a local function does and it does it with the clean
semantics of a function call.

When this idea came up in comp.lang.c you could not see the point, yet
you appear to have a use-case common enough that you have a solution
worked out using gotos.

> If it looks better than what I'd come up with, then I'll use that instead.

What looks better is always going to be an unreliable and subjective
measure, but calling a named function almost certainly scales better and
will allow for better structuring (such as when one block needs to use
another one).

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


Re: CFG Python

2017-12-30 Thread Ben Finney
Peter Otten <__pete...@web.de> writes:

> > Let's say I vreated my own CFG in python, How can I […]
>
> Remember, context free grammars may be fine, but context free
> questions aren't ;)

+1 QotW

-- 
 \“The problem with television is that the people must sit and |
  `\keep their eyes glued on a screen: the average American family |
_o__) hasn't time for it.” —_The New York Times_, 1939 |
Ben Finney

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


Re: CFG Python

2017-12-30 Thread Peter Otten
Ranya wrote:

> Let's say I vreated my own CFG in python, How can I check now if a
> sentence match this grammar (return true) or it doesn't match it (return
> false and the wrong element in the grammar), How can I do this ?

Remember, context free grammars may be fine, but context free questions 
aren't ;)

Is this question nltk-related? If so, here's one way (using a grammar found 
at http://www.nltk.org/book/ch08.html):

>>> import nltk
>>> grammar = nltk.CFG.fromstring("""
...   S -> NP VP
...   VP -> V NP | V NP PP
...   PP -> P NP
...   V -> "saw" | "ate" | "walked"
...   NP -> "John" | "Mary" | "Bob" | Det N | Det N PP
...   Det -> "a" | "an" | "the" | "my"
...   N -> "man" | "dog" | "cat" | "telescope" | "park"
...   P -> "in" | "on" | "by" | "with"
...   """)
>>> parser = nltk.RecursiveDescentParser(grammar)
>>> def check(sentence, parser=parser):
... return parser.parse_one(sentence) is not None
... 
>>> check("Mary saw the telescope".split())
True
>>> check("Mary saw the saw".split())
False
>>> check("Mary saw the chicken".split())
Traceback (most recent call last):
[...]
ValueError: Grammar does not cover some of the input words: "'chicken'".


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


Re: Goto (Posting On Python-List Prohibited)

2017-12-30 Thread Ian Kelly
On Sat, Dec 30, 2017 at 8:41 AM, bartc  wrote:
> (I had introduced a special language feature just for this kind of thing,
> but it was unsatisfactory. Goto was simpler and understood by everyone. And
> portable to any other language - that hasn't done away with goto. But it
> worked like this (not Python):
>
> a:=20
>
> case a
> when 10 then
> fred::
> println "one"
>
> when 20 then
> @fred
> println "two"
>
> end
>
> Output is "one" "two" when a is 20.
>
> fred:: names a block, and @fred 'calls' that block, without having to move
> it out of context. Actually this goes beyond what 'goto' can do, as it can
> also 'come back'. But as you can see, it looks a bit naff. A bit 1970s.)

BASIC had this feature in the form of the GOSUB statement. Although it
used an explicit rather than implicit RETURN.

BASIC was an awful language for developing programs of any size,
though. Without actual subroutines and with only one variable scope,
most people developed the practice of using GOSUB and designating
specific global variables as pseudo-arguments in order to have some
limited form of parameter passing. That was the kind of environment
where GOTO really, really sucks and produces the monstrous spaghetti
code that gives it its bad reputation. With the restrictions of
languages like C (i.e. only allowing GOTO within a function) and with
a reasonable level of restraint, I don't think that the use of GOTO is
really that big of a deal.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Goto (Posting On Python-List Prohibited)

2017-12-30 Thread MRAB

On 2017-12-30 18:21, bartc wrote:

On 30/12/2017 16:53, mm0fmf wrote:

On 30/12/2017 14:41, bartc wrote:

it looks a bit naff


Understatement of 2017.


I'm honest about my own ideas, but my remarks were about the use of
special symbols such as "::" and "@".

Before completely dismissing it however, you should look at how another
language such as Python can achieve the same thing.

Namely, take any block of code within a function, and allow it to be
executed or shared from anywhere else in the function, with the minimum
of disruption.

If it looks better than what I'd come up with, then I'll use that instead.

Perhaps what you want is something closer to a local named subroutine 
that can directly access the local variables.

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


Re: Goto (Posting On Python-List Prohibited)

2017-12-30 Thread bartc

On 30/12/2017 16:53, mm0fmf wrote:

On 30/12/2017 14:41, bartc wrote:

it looks a bit naff


Understatement of 2017.


I'm honest about my own ideas, but my remarks were about the use of 
special symbols such as "::" and "@".


Before completely dismissing it however, you should look at how another 
language such as Python can achieve the same thing.


Namely, take any block of code within a function, and allow it to be 
executed or shared from anywhere else in the function, with the minimum 
of disruption.


If it looks better than what I'd come up with, then I'll use that instead.


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


Re: Goto (Posting On Python-List Prohibited)

2017-12-30 Thread mm0fmf

On 30/12/2017 14:41, bartc wrote:

it looks a bit naff


Understatement of 2017.

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


CFG Python

2017-12-30 Thread Ranya
Let's say I vreated my own CFG in python, How can I check now if a sentence
match this grammar (return true) or it doesn't match it (return false and
the wrong element in the grammar), How can I do this ?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Goto (Posting On Python-List Prohibited)

2017-12-30 Thread bartc

On 30/12/2017 03:05, Lawrence D’Oliveiro wrote:

On Saturday, December 30, 2017 at 12:12:23 PM UTC+13, bartc wrote:

Looking at 14 million lines of Linux kernel sources, which are in C,
over 100,000 of them use 'goto'. About one every 120 lines.


That kind of thing leads to spaghetti code.

Here  is an example I like to bring 
up: writing a Python extension module in C. As you know, this requires a lot of 
careful memory management to cope with errors and avoid either memory leaks or 
double-frees. The coding convention I came up with looks like this:

 ... initialize pointers to allocated storage to NULL ...
 do /*once*/
   {
 ... processing ...
 allocate some storage;
 if (error)
 break;
 ... more processing ...
 allocate more storage;
 if (error)
 break;
 ... even more processing ...
   }
 while (false);
 ... free allocated storage ...

Basically, it becomes possible to satisfy yourself, by inspection, that every 
possible control path through the above code will pass once, and only once, 
through the storage deallocation.

Things get slightly more complicated where allocation has to happen in a loop. 
Actually, that’s where the interesting cases happen. My technique can be 
adapted to cope elegantly with this, too--see the code.



I tend to use goto to share small sequences of code:

   if cond1:
  A
  B
   elif cond2:
  C
   elif cond3:
  D
  B
   elif cond4:
  C
   ...

Here, A, B, C, D represent small blocks of code. The conditions have to 
be tested in this order.



B and C occur twice, so a goto is a quick way to reuse B and C without 
needing to duplicate code, or go through the upheaval of extracting them 
to functions. (And then the code develops so that the two Bs /are/ 
different, and then you have to get rid of the function. Or the second C 
was temporary anyway.)


Any other way of doing it will obfuscate the structure:

   if cond1:
  A
   elif cond2 or (not cond3 and cond4):
  C
   elif cond3:
  D

   if cond1 or (not cond2 and cond3):
  B

I can no longer be sure if this right. Plus executing A, C, D can change 
the conditions if they are tested again.


(I had introduced a special language feature just for this kind of 
thing, but it was unsatisfactory. Goto was simpler and understood by 
everyone. And portable to any other language - that hasn't done away 
with goto. But it worked like this (not Python):


a:=20

case a
when 10 then
fred::
println "one"

when 20 then
@fred
println "two"

end

Output is "one" "two" when a is 20.

fred:: names a block, and @fred 'calls' that block, without having to 
move it out of context. Actually this goes beyond what 'goto' can do, as 
it can also 'come back'. But as you can see, it looks a bit naff. A bit 
1970s.)


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


Re: Goto (Posting On Python-List Prohibited)

2017-12-30 Thread Peter J. Holzer
On 2017-12-29 19:09:35 -0500, Dennis Lee Bieber wrote:
> On Fri, 29 Dec 2017 23:12:22 +, bartc  declaimed the
> following:
> >Looking at 14 million lines of Linux kernel sources, which are in C, 
> >over 100,000 of them use 'goto'. About one every 120 lines.
> >
> 
>   C is a language that predates the "structured programming" concepts of
> the late 70/early 80.

I don't think this is correct. Structured programming is much older:
ALGOL 60 was already a block structured language and Dijkstra wrote
"goto considered harmful" in the late 1960s. Pascal appeared in 1970, C
in 1974. To me (who learned to program in BASIC on a CP/M machine), C
is very much a structured programming language. If structured
programming gained traction around 1980, it might even have been because
structured languages like C with good performance became widely
available.

That said, C lacks exception handling (well, there is setjmp/longjmp,
but ...) and multi-level break/continue, so goto is often the cleanest
way to abort what you are doing and start to clean up. Python has
exception handling, and that removes most of the cases where you would
use goto in C (the rest is probably mostly in micro-optimizations: If
you care about the run-time difference between a goto and a subroutine
call, you probably shouldn't use Python in the first place).

hp

-- 
   _  | Peter J. Holzer| we build much bigger, better disasters now
|_|_) || because we have much more sophisticated
| |   | h...@hjp.at | management tools.
__/   | http://www.hjp.at/ | -- Ross Anderson 


signature.asc
Description: PGP signature
-- 
https://mail.python.org/mailman/listinfo/python-list