code blocks in Python

jlfivn 19dmcelwaine.student at daos.uk
Fri Mar 25 06:12:30 EDT 2022


On Monday, 24 November 2003 at 23:54:49 UTC, John Roth wrote:
> "Hung Jung Lu" <hungj... at yahoo.com> wrote in message
> news:8ef9bea6.03112... at posting.google.com...
> > Skip Montanaro <sk... at pobox.com> wrote in message
> news:<mailman.1035.106970... at python.org>...
> > >
> > I come back again to repeat it one more time: the compile() function
> > already exists and works in Python. Before you do your posting, please
> > think about the compile() function first. (Do I need to say it one
> > more time? I don't mind.)
> So what?
> Functionality is not added to Python simply because it looks like
> a logical extension of something else that already exists. First,
> you need to show a compelling use case.
> So far, I've seen one thing in your proposal: dynamic binding
> of free variables in a function, rather than static binding. All
> questions of syntax aside, please show me why this matters,
> bearing in mind that I've never programmed in a language
> that has this, and am not going to be convinced by references
> to such languages.
> While I'm not *the* person that has to be convinced (that's Guido),
> I'm probably representative. If you don't manage a compelling
> case for why dynamic binding is a useful option, then you're not going
> to get anywhere with this proposal.
> By the way - if I understand the guts of the proposal, the compile
> function has nothing to do with it, and wouldn't be used to implement
> it in any case.
> John Roth

One use case is modifying the underlying bytecode of the code block to allow features that are not implemented or should not be implemented in python but still make sense in context. For example python-goto is a module that allows you to add goto statements to python code. Currently it has to be applied as a decorator to a function which then needs to be called. Being able to create a code block and then run it instead of having to rap it in a function could be very useful is such cases.
I propose the following syntax:

code_block :                  #start a code block
    print("foobar")

#the code block would be executed immediately
#would print "foobar"

code_block as my_code: #save the code to the named variable;does not execute immediately
    print("foobar")
#no output but code is in my_code

exec(my_code)
#would print "foobar"

@with_goto                                                              #the code block would be past to the decorator then executed
code_block:
    print("ignore the fact that I'm using goto")
    goto .cheat
    print("goto is a bad idea")
    label .cheat

#output :"ignore the fact that I'm using goto"




More information about the Python-list mailing list