Function attributes

Steve Howell showell30 at
Sat Feb 13 10:53:09 CET 2010

On Feb 10, 5:59 am, Muhammad Alkarouri <malkaro... at> 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(
        def recurse(n):
            print preamble, n, postamble
            if 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:

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