Why can function definitions only use identifiers, and not attribute references or any other primaries?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Fri Apr 24 10:27:15 CEST 2009

On Thu, 23 Apr 2009 10:48:57 -0700, Scott David Daniels wrote:

> I am afraid it will make it too easy to define functions in other
> modules remotely, a tempting sharp stick to poke your eye out with. 

It's not terribly difficult to do so already:

>>> def spam():
...     return "spam spam spam"
>>> import math
>>> math.spam = spam
>>> math.spam()
'spam spam spam'

> Note
> also, that it will not be so easy to find the definition of a function
> provided as a argument to a failing function.  Right now you can get the
> function name and (with a bit more effort) its module. Imagine debugging
> a pile of code that includes a module with:
>      import random
>      def random.random():
>          return .42


>>> import random
>>> random.random = lambda: 0.42
>>> random.random()
>>> random.random.__name__
>>> random.random.__module__

Sure, if somebody wants to really work at it, they could create a 
function that looks exactly like the original, including claiming to come 
from the same module, but that's possible now anyway.

I don't think the proposed syntax is useful because it doesn't actually 
gain us anything. Currently, you add a function to a class at class 
creation time:

class Spam(object):
    def spam(self):
        return "spam spam spam"

Adding functions to a class after the class already exists is rare, but 
not unheard of. Currently you can do this:

def ham(self):
    return "ham is not spam"

Spam.ham = ham
del ham  # if you can be bothered

And you're done. The proposal gives us this:

class Spam(object):
    pass  # Need to have a class before you can add methods to it.

def Spam.spam(self):
    return "spam spam spam"

def Spam.ham(self):
    return "ham is not spam"

Whatever benefit there might be from doing this, it's so minor I don't 
think it's worth the effort to implement it. Unlike decorators, I'd be 
surprised if it opens the door to bigger and better things.


More information about the Python-list mailing list