Rafael Higa
Rafael Higa

Reputation: 725

Python getattr in string

I have a string x = 'hello world', and I'm trying to uppercase it with getattr()

I understand that getattr(x, 'upper') returns x.upper, which is different from x.upper(), and then returns <built-in method upper of str object at 0x7fd26eb0e2b0>

I also understand that, using getattr(str, 'upper)(x), I can get the desired result, 'HELLO WORLD'

But why and how can I get the uppercase x calling getattr(x, 'upper'), passing x, and not str class, as a parameter? Is it possible? And why?

Upvotes: 0

Views: 1032

Answers (1)

user2390182
user2390182

Reputation: 73498

Just call the returned function:

x = 'hello world'
getattr(x, 'upper')()  # note the extra "()"
# 'HELLO WORLD'

With the given information, you don't need getattr at all and could just use x.upper(). As you might be in a dynamic context where you would have to call possibly multiple methods on multiple strings, you may be interested in operator.methodcaller and operator.attrgetter which might make some of your code more reusable:

from operator import attrgetter, methodcaller

up = methodcaller("upper")
up(x)
'HELLO WORLD'
up("foo")
'FOO'

up2 = attrgetter("upper")
up2(x)()
'HELLO WORLD'

Upvotes: 4

Related Questions