Function attributes

Steve Howell showell30 at yahoo.com
Sat Feb 13 04:53:09 EST 2010


On Feb 10, 5:59 am, Muhammad Alkarouri <malkaro... at gmail.com> wrote:
> Hi everyone,
>
> What is the simplest way to access the attributes of a function from
> inside it, other than using its explicit name?
> In a function like f below:
>
> def f(*args):
>     f.args = args
>     print args
>
> is there any other way?
> I am guessing the next question will be: should I really care? It just
> feels like there should be a way, but I am not able to verbalise a
> valid one at the moment, sorry.
>

You should care. :)

You can avoid referring to f twice by using an inner method with a
name that is less subject to change or influence from outside forces:

    def countdown_function_that_might_get_renamed(
            n,
            preamble,
            postamble):
        def recurse(n):
            print preamble, n, postamble
            if n:
                recurse(n-1)
        recurse(n)

    countdown_function_that_might_get_renamed(10, "before", "after")

Note that the example makes the recursive call more concise, by
avoiding the need to resend the parameters that don't change during
the recursion ("preamble" and "postamble").  Of course, you do trade
off some terseness with the inner method, but it's only two lines of
code and one level of indentation.

For a somewhat related discussion see this short thread:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/197221f82f7c247b

In particular see Gabriel's response to me.  The fact that you are
saving off f.args makes me think that you are solving a problem
similar to mine, but I could be wrong.




More information about the Python-list mailing list