What could 'f(this:that=other):' mean?

Jonathan Fine jfine at pytex.org
Wed Jan 5 15:49:14 EST 2005


Giudo has suggested adding optional static typing to Python.
(I hope suggested is the correct word.)
   http://www.artima.com/weblogs/viewpost.jsp?thread=85551

An example of the syntax he proposes is:
 > def f(this:that=other):
 >     print this

This means that f() has a 'this' parameter, of type 'that'.
And 'other' is the default value.

I'm going to suggest a different use for a similar syntax.

In XML the syntax
 >  <element this:that='other'>
is used for name spaces.

Name spaces allow independent attributes to be applied to an
element.  For example, 'fo' attributes for fonts and layout.
XSLT is of course a big user of namespaces in XML.

Namespaces seems to be a key idea in allow independent
applications to apply attributes to the same element.

For various reasons, I am interested in wrapping functions,
and supplying additional arguments.  Namespaces would be
useful here.  Decorators, by the way, are ways of wrapping
functions.  Namespaces might make decorators a bit easier
to use.

Here's an example of how it might work.  With f as above:
 > f(this:that='value')
{'that': 'value'}

Do you see?  The syntax of def makes 'this' a dictionary.
And the syntax of the call adds an item to 'this'.
This aligns nicely with XML syntax and semantics.

One could extend **kwargs similarly.
 > def g(***nsargs):
 >     print ***nsargs
 >
 > g(this:that='other', that:this='more')
{'this': {'that': 'other'}; {'that': {'this': 'more'}}

All the namespace args are gathered into a dict of dicts.

Thus, this suggestion is mostly syntactic sugar for
f(this=dict(that='other), that=dict('this'=other))

(Have I got this right? - I'm only up to Python 2.2 at
home.  This is how I remember 2.4.)


Back to optional static typing.  A common idiom is
 >  def return_dict(data=None):
 >      if data is None:
 >           data = {}
         # etc

This avoid the newbie gotcha in
 >  def return_dict(data={}:
 >       # etc

So to write this using the suggested syntax one has:
 >  def return_dict(data:dict=None):
 >       # oops!


So now some final comments.
1.  I have no opinion yet about optional static typing.
2.  Calls of function f() should outnumber definitions of f().
(I'm not totally convinced of this - for example __eq__ may
be defined in many classes, but called by few functions.
Frameworks often have functions as parameters.)
3.  Granted (2), perhaps function calls are first in the
queue for syntactic sugar.

-- 
Jonathan
http://www.pytex.org




More information about the Python-list mailing list