alias method definitions / syntactic sugar suggestion

Terry Reedy tjreedy at udel.edu
Thu Mar 5 23:50:31 EST 2009


Tennessee Leeuwenburg wrote:
> I'm not sure if this problem I face affects many other people, but I'll 
> just describe it and see what kind of feedback I get.
> 
> I have a suggestion for a new piece of Python syntax when defining 
> methods. I have seen the following done, and have done it myself
> 
> 
> class FanstasticClass:
> 
>     def __init__(self):
>         self.someFantasticMethod("Hello")
> 
>     def someFantasticMethod(self, argument = True):
>         print argument
>  
>     justAsFantastic = someFantasticMethod

> In order to set up a second method, justAsFantastic, which is just an 
> alias to someFantasticMethod

This is fairly rare, I believe.

> The shortcoming of this approach is that supposing we have some 
> unfamiliar codebase. In my method I see a call to 
> someObject.justAsFantastic("Wahoo"). In order to find that method, I do 
> a file search for "def justAsFantastic(" in order to make sure (a) I 
> only get method definitions and (b) I don't get any extraneous methods.

The search will also fail if there is other than a single space between 
'def' and 'meth_name'.

> This is especially relevant to methods which might be commonly used as 
> variable names elsewhere in the code.
> 
> I suggest allowing the following syntax:
> 
>    def justAsFantastic = someFantasticMethod
> 
> which will *do* exactly the same thing, but by a syntactic marker that 
> the variable justAsFantastic points to a method.
> 
> 
> Comments appreciated!

Tack '# def justAsFantastic' on the end of the line and the search will 
work.

The the def search also does not work with methods set from outside.

class C:...

def _(s,args): pass
C.somemeth = _
# or setattr(C, 'somemeth', _)

nor would the proposal work with an aliasing decorator

@alias('justAsFantastic')
def someFantasticMethod(args): ...

which some would prefer if doing very many aliases.  Better to just 
search for 'justAsFantastic'.

tjr






More information about the Python-list mailing list