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?
3 Answers 3
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__
Comments
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__
Comments
You don't need to call this function and simply use name
>>> str.capitalize.__name__
str.capitalize.__name__orgreeting.capitalize.__name__?greeting.capitalizeis a function object, and that object has a.__name__attribute that you can access. Butgreeting.capitalize()calls the function object and returns the capitalized version of thegreetingstring, 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 dostr.capitalize()because when you call the "raw"str.capitalizefunction you need to pass it a string argument to capitalize.