10

I want to change the function name according to result obtained from another function but the function definition remains same How can i do this i tried the following example but it didn't work

def f(text):
   def x(text):
     return text+"example"
   name=x(text)
   def name(y):
     return y
   return name
p=f("hi ")
print p("hello")
print p.__name__

OUTPUT

hello
name

But i want the function name p.__name__ as "hi example" not name

2
  • 5
    Why does one want to do this? Commented Sep 14, 2012 at 5:55
  • 2
    @esaelPsnoroMoN: can't speak for the OP, but personally I have done this to tailor documentation for closures, dynamically assigning __doc__ as well. A closure retains the internal name, which arguably should be encapsulated. Commented Sep 14, 2012 at 6:47

1 Answer 1

8

You can simply assign to __name__:

def f(text):
   def r(y):
     return y
   r.__name__ = text + "example"
   return r
p = f("hi ")
print (p("hello")) # Outputs "hello"
print (p.__name__) # Outputs "hi example"

Note that a function name does not have any influence on the function's behavior though, and does not have any meaning except as a part of the string representation or a debugging aid.

Sign up to request clarification or add additional context in comments.

2 Comments

I'm not so sure __name__ is an implementation detail, it's listed as part of the data model.
@MatthewTrevor Oh, you're totally right - it's even declared writable. Fixed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.