473,591 Members | 2,842 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

grammar for where/letting/with and suite expressions (thunks etc)


We have where syntax in combination with suite expression syntax (bear with me,
I think a good synergy will emerge ;-)

http://groups.google.co.uk/groups?se...t%40python.org
http://groups.google.co.uk/groups?se...individual.net

are the key referneces for background (I'm just repeating from Oren's post for convenience).

The first suggests a grammar mod for its proposed "with" (rather than the name "where"),
but it doesn't cover the variations we are discussing now.

If "where" is not a good word, and "with" is destined for use that may clash, how about "letting"
or if that's too long, "per" ? Anyway, the new stuff adds the new compound statements

Here's a cut at Grammar modifications: (though I guess the grammar in

http://www.python.org/doc/current/ref/grammar.txt

is really closer to actual parsing. BTW, how is the Grammar file that comes with the sources maintained along with the former?
E.g., I didn't see how the latter parses a non-assignment expression as a statement, e.g.
NAME '(' ')'
Maybe I have a glitched version of Grammar?

But anyway, since I did this already, it will serve as a sketch:

compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef | letting_stmt | named_suite_stm t
small_stmt: tiny_stmt | flow_stmt | import_stmt | global_stmt | exec_stmt
tiny_stmt: expr_stmt | print_stmt | del_stmt | pass_stmt | import_stmt | assert_stmt

letting_stmt: tiny_stmt 'letting' ( let_stmt | ':' suite )
let_stmt: named_suite_stm t | assignments_stm t
assignments_stm t: expr_stmt??

named_suite_stm t: NAME suite_expr
suite_expr: '::' suite | parameters ':' suite | 'def' parameters ':' suite
I split out a tiny_stmt subset of small_stmt so we won't accept "continue letting x=5" and such.

Basically we have either

<tiny_stmt> letting:
<suite> # meaning any possible suite, but obviously should concern itself
# with binding names for tiny_stmt to use

or
<tiny_stmt> letting <let_stmt>

where <let_stmt> binds names by assignment, or by a named_suite_stm t, e.g, (assuming a bare expression is parsed as an expr_stmt)

foo(x) letting x=1 # simple let_stmt as assignmerns_stm t
foo(x, y) letting x,y = 1,2 # assignments_stm t should exclude augassign operators so is not ==
safe_open(tk, 'data.txt') letting tk(f):
# this suite is thunk tk's body, called back by foo, passing safely opened f as arg
longest = max(len(line) for line in f) # save result longest in local namespace

If you put the ':' after letting, you introduce a general suite whose bindings will override any name bindings
otherwise used by the preceding tiny_stmt, e.g, the above in letting: form

foo(x) letting:
x=1 # simple let_stmt as assignmerns_stm t
foo(x, y) letting:
x,y = 1,2 # assignments_stm t should exclude augassign operators so is not ==
safe_open(tk, 'data.txt') letting:
tk(f):
# this suite is thunk tk's body, called back by foo, passing safely opened f as arg
longest = max(len(line) for line in f) # save result longest in local namespace

Note that tk(f): and its suite work just like a def, except for binding a thunk instead. You can also
bind tk to the thunk expression, analogous to binding a lambda to what a def name would bind, e.g.,
This is will do the same as above, though the isolated (f): may look unfamiliar, ;-)
safe_open(tk, 'data.txt') letting:
tk = (f):
# this suite is thunk tk's body, called back by foo, passing safely opened f as arg
longest = max(len(line) for line in f) # save result longest in local namespace

Since letting: introduces a full-fledged suite, nested lettings of both kinds become possible, e.g.

foo(tk, func, *args, **kw) letting:
kw = dict(tuplist) letting:
tuplist = [(1,'one'), (2,'two')] # silly example
args = d.values() letting d:: # d becomes dict of suite bindings
a = 123
def foo(x):
tk(logitem): # tk becomes thunk with body defined in following suite
print logitem
def func(x, y): # func is ordinary but transient function
return 'Hi from fun with', (x,y)

What I haven't covered is the same-indentation aligned 'with' following a statement, as seems permitted
in Nick reference post where he says
"""
Grammar Change
--------------
Current::
statement ::= stmt_list NEWLINE | compound_stmt

New::
statement ::= (stmt_list NEWLINE | compound_stmt) [local_namespace]
local_namespace ::= "with" ":" suite
"""

I'll have to leave that for now. Anyway, hope this all evolves into something neat ;-)

Actually, I don't like "letting" that much as the word. I keep having to type where^H^H^H^H^H letting ;-)
"per" would be short, but maybe not mnemonic enough. "with" might be good, but I am allowing
with not to have a colon, e.g. with a single thunk definition for a function call:

final_status = safe_open(tk, 'data.txt') with tk(f):
longest = max(len(line) for line in f)

Since my 'letting' is effectively a tiny_stmt trailer and anticipated with usage is more header like,
maybe that is enough to disambiguate. I'll have to see the future with grammar.
Hm, Let's see if Nick Coghlan's summary of examples can be handled with letting:

Examples
--------

# Statement local functions (from Andrey Tatarinov)
# aka How to cope if lambda goes away :)
res = [ f(i) for i in objects ] with:
def f(x):
#do something
OK as is.

# Declaring properties (from Nick Coghlan)
class C(object):
x = property(get, set) with:
def get(self):
pass
def set(self, value):
pass
OK as is.

# Design by contract (from Nick Coghlan)
@dbc(pre, post)
def foo():
pass
with:
def pre():
pass
def post():
pass

Problem, but if decorator expressions were allowed to have letting,

@dbc(pre, post) letting:
def pre(): pass
def post(): pass
def foo():
pass

# Singleton classes (from Paul Rubin)
C = C() with:
class C:
pass
OK as is.

# Complex default values (from Carlos Ribeiro)
def f(x=default()):
pass
with:
def default():
pass

Since this is not decorated, I can do it with an anonymous def suite expression
which, being an expression (making the whole a simple expr assignment) allows letting:

f = def(x=default() ):
pass
letting: # dedent to this line ends anonymous def suite and goes back to expression context
def default():
pass

To show the expression nature better, (not that it's a preferred spelling ;-),
the expression is parenthesized, and closes with the closing ')'

f = (def(x=default( )):
pass
) letting:
def default():
pass
or uglier:
f = (def(x=default( )):
pass) letting:
def default():
pass

You could even write a one-liner for this, since the suites are one-liner passes ;-)

f = (def(x=default( )):pass) letting default=(def(): pass)

So there was really only a problem with the decorator.
But I gotta go for now.

Regards,
Bengt Richter
Jul 19 '05 #1
0 1493

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
3410
by: Peri | last post by:
I'm trying to create Python parser/interpreter using ANTLR. Reading grammar from language refference I found: or_expr::= xor_expr | or_expr "|" xor_expr For me it looks like infinite recursion. And so it says ANTLR. Maybe I don't understand EBNF notation. For me it should look like this. or_expr::= xor_expr | xor_expr "|" xor_expr and in ANTLR grammar file like this:
37
2783
by: michele.simionato | last post by:
Paul Rubin wrote: > How about macros? Some pretty horrible things have been done in C > programs with the C preprocessor. But there's a movememnt afloat to > add hygienic macros to Python. Got any thoughts about that? "Movement" seems quite an exaggeration. Maybe 2-3 people made some experiments, but nobody within the core Python developers seems to be willing to advocate the introduction of macros. > Why should you care whether the...
31
2413
by: Brian Sabbey | last post by:
Here is a pre-PEP for what I call "suite-based keyword arguments". The mechanism described here is intended to act as a complement to thunks. Please let me know what you think. Suite-Based Keyword Arguments ----------------------------- Passing complicated arguments to functions is currently awkward in Python. For example, the typical way to define a class property winds up polluting the class's namespace with the property's get/set...
0
1686
by: Chad Whitacre | last post by:
Hey all, I've been playing around with the parser module, and based on the documentation I would expect all symbols in a parse tree to be part of the grammar. For example, I find this line in the symbol module docs: Refer to the file Grammar/Grammar in the Python distribution for the definitions of the names in the context of the language grammar. However, the program below gives me a human-readable parse tree (also
12
2166
by: Ali | last post by:
I have the following web page with a script in it. <html> <head> <title>Make Your Own Objects test</title> <script>
4
1900
by: ben | last post by:
getting a bit confused with the details of how c's grammar is specified, especially when you get self-reference like in this: postfix-expression: primary-expression postfix-expression postfix-expression ( argument-expression-listopt ) postfix-expression . identifier postfix-expression -> identifier postfix-expression ++
3
8137
by: junky_fellow | last post by:
I got one link to the ANSI C Grammar http://www.lysator.liu.se/c/ANSI-C-grammar-y.html However, I don't know how to understand this grammar. I am not a Computer Science Guy. Can anybody please help me about how to understand this grammar. Is there any good book on this ? Or anybody knows about some link from where a beginner like me start of ? Thanx for any help in advance ...
4
2790
by: junky_fellow | last post by:
Hi, Is any one aware of some link that has the grammar files (yacc and lex files) for command interpreter like shell ? thanks a lot for any pointers ....
3
2376
by: xahlee | last post by:
In the past weeks i've been thinking over the problem on the practical problems of regex in its matching power. For example, often it can't be used to match anything of nested nature, even the most simple nesting. It can't be used to match any simple grammar expressed by BNF. Some rather very regular and simple languages such as XML, or even url, email address, are not specified as a regex. (there exist regex that are pages long that tried...
0
7934
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
7870
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
7992
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8225
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5400
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3850
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
3891
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2378
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1465
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.