Asif Raza
Asif Raza

Reputation: 3705

How to get a function's name as string?

In Python, how do I get a function's name as a string?

I want to get the name of the str.capitalize() function as a string. It appears that the function has a __name__ attribute. When I do

print str.__name__

I get this output, as expected:

str

But when I run str.capitalize().__name__ I get an error instead of getting the name "capitalize".

> Traceback (most recent call last):
> File "string_func.py", line 02, in <module>  
>    print str.capitalize().__name__
> TypeError: descriptor 'capitalize' of 'str' object needs an argument

Similarly,

greeting = 'hello, world'
print greeting.capitalize().__name__

gives this error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute '__name__'

What went wrong?

Upvotes: 3

Views: 2979

Answers (3)

Erdenezul
Erdenezul

Reputation: 597

You don't need to call this function and simply use name

>>> str.capitalize.__name__

Upvotes: 1

Sagar V
Sagar V

Reputation: 12478

Let's start from the error

Traceback (most recent call last):
File "", line 1, in
AttributeError: 'str' object has no attribute 'name'

Specific

AttributeError: 'str' object has no attribute 'name'

You are trying

greeting = 'hello, world'
print greeting.capitalize().__name__

Which will capitalize hello world and return it as a string.

As the error states, string don't have attribute _name_

capitalize() will execute the function immediately and use the result whereas capitalize will represent the function.

If you want to see a workaround in JavaScript,

Check the below snippet

function abc(){
  return "hello world";
}

console.log(typeof abc); //function
console.log(typeof abc());

So, don't execute.

Simply use

greeting = 'hello, world'
print greeting.capitalize.__name__

Upvotes: 4

Asif Raza
Asif Raza

Reputation: 3705

greeting.capitalize is a function object, and that object has a .__name__ attribute that you can access. But greeting.capitalize() calls the function object and returns the capitalized version of the greeting string, and that string object doesn't have a .__name__ attribute. (But even if it did have a .__name__, it'd be the name of the string, not the name of the function used to create the string). And you can't do str.capitalize() because when you call the "raw" str.capitalize function you need to pass it a string argument that it can capitalize.

So you need to do

print str.capitalize.__name__

or

print greeting.capitalize.__name__

Upvotes: 11

Related Questions