1

Further to my previously question that has helpfully answered, a new related question is:

How can I 'append' a user inputted transcendental function onto a math. prefix (math.user_fn) that python can than work with in the usual manner? Sorry being beginner, I'm not sure of the precise terminology I shot be using, but I think I'm asking how to change object type in this case? e.g.

v1 = input("Type a transcendental function e.g. 'sin' or 'exp': ")

so that I can then compute something like:

math.v1(2.3) 
Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
mb49
  • 63
  • 1
  • 5
  • The accepted answer uses getattr. – Josh Lee Jan 27 '17 at 15:38
  • Possible duplicate of [Calling a function of a module from a string with the function's name in Python](http://stackoverflow.com/questions/3061/calling-a-function-of-a-module-from-a-string-with-the-functions-name-in-python) – Josh Lee Jan 27 '17 at 16:47

1 Answers1

1

You can't do it in the usual way (i.e dot access). You can get it and call it on the spot with getattr. The fact is that math.v1 will perform a __getattribute__ call on the module object and look for an attribute who's name isn't the value of v1 but, rather, the string 'v1' itself.

That fails and there's no means to change it.

You should just opt for getattr, this supports dynamic attribute fetching:

getattr(math, v1)(2.3)

this attempts to grab an attribute whos' name equals the value of v1 and then calls it on the spot. It's a shorter version for:

func = getattr(math, v1)
func(2.3)
Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253