0

I can access a functions' func_dict easily if I write its name inside it:

def func(a):
    print('{} {}'.format(func.prefix, a))

func.prefix = 'something'
func(4)

Is there any way I can access prefix without having to write func again, similar to self in class methods?

Martín Fixman
  • 9,055
  • 9
  • 38
  • 46
  • Are you sure `func` should not be a method of a class instead? – chepner Nov 25 '15 at 16:09
  • 1
    Or perhaps `prefix` should be an argument with a default value? – chepner Nov 25 '15 at 16:11
  • Frankly, the best solution (that involves no cheating with nonsense like adding a defaulted `self` argument to a function) is to make a callable class, per the [second answer](https://stackoverflow.com/a/3109542/364696) on the [linked question](https://stackoverflow.com/questions/3109289/how-can-python-function-access-its-own-attributes). You can even do additional tricks, like assigning the values at the class definition layer, then saying `func = func()`, which will replace the class definition with a single instance of the class (that has a `self` that can access the class variables). – ShadowRanger Nov 25 '15 at 16:22

1 Answers1

-1

You just did it.

def func(a):
    print('{} {}'.format(func.prefix,a))

If you call it by itself without setting prefix you will get an AttributeError since prefix will not yet have been defined

By defining func.prefix='something', now when you call func(4) you will get something 4 as an output. And you can just keep redefining func.prefix and it will update the Attribute in func.

Unless there is something more to your question, you've done it correctly already.

Chrispresso
  • 3,660
  • 2
  • 19
  • 31
  • 1
    No point in answering if there is nothing more to add. I think the greater question here is how to access the namespace without using the name of the function, so that if `func()` is renamed all of the internal references will work without also having to be changed. – MrAlexBailey Nov 25 '15 at 16:01
  • Jkdc is right, that was my point. – Martín Fixman Nov 25 '15 at 17:05