Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
def xxx() question
#1
Hi,

The other day i came across an app that used somthing like this:
def myDef():
    myDef.msg = myDef.msg[.....]
    .....

myDef.msg = 'this is a message'
I cannot find much documentation concerning this . msg "feature".
It seems to be the only attribute for a def() even outside itself.
Is it old, is it new, is it almost deprecated ?
What is the big idea behind it?
Why not call the function with the text as argument?
thx,
Paul
It is more important to do the right thing, than to do the thing right.(P.Drucker)
Better is the enemy of good. (Montesquieu) = French version for 'kiss'.
Reply
#2
First of all, terminology: it's not a "def", it's a "function". Functions have been able to have attributes since Python 2.7 at least. I've used them when I want to associate some state with a function. Normally, you'd hold state in a class, but some problems don't really need classes and a function will do. In my case, I had a function that would execute a command and there were different commands associated with a string input. Of course, one way to do this is just with classes and the inherent polymorphism you get from inheritance.

So, I had code that looked like (with most error handling omitted for brevity)

def execute(command, args):
    try:
        _execute = execute._commands[command]
    except KeyError:
        raise UnknownCommandException(command)
    else:
        return _execute(*args)
as well as a way to register commands with a decorator:

def _register(command):
    def decorate(f):
        execute._commands[command] = f
        return f

    return decorate

execute.register = _register
It's a different way to do dispatching than polymorphism and the idea was based on the standard library functools.singledispatch function.

You haven't provided many details about the example or where it came from, so it's difficult to infer why the authors might have chosen to design it that way.
Reply
#3
OK, i was not aware that these atrributes are not predefined.
To convince myself i created a function def xxx():
...
and then you can make xxx.chicken = '...' do something.
I also see why the authors used this, probably because the function calls itself,
and the function alters the original msg (ticker app)
thx,
Paul
It is more important to do the right thing, than to do the thing right.(P.Drucker)
Better is the enemy of good. (Montesquieu) = French version for 'kiss'.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020