0

I have some imported functions from package import fizz, buzz and I want to map them to a variable func from a string arg.

class Whatever(object):
    def __init__(self, func_name='fizz'):
        try:
            self.func = vars()[func_name]
        except KeyError:
            print "Bad func_name"
            raise

But vars() only captures the local namespace, and I don't want to allow access to globals(). Any ideas? Or should I just go with if-else logic?

9
  • This might be what you're looking for: docs.python.org/3/library/functions.html#exec Commented May 10, 2017 at 19:03
  • 1
    Why don't you pass the function directly to the initializer: def __init__(self, func=fizz) Commented May 10, 2017 at 19:03
  • But basically, if you want to access some global name outside the global scope using a string, then you sort of have to use globals, or even worse, something like exec or eval. Commented May 10, 2017 at 19:04
  • Thank you, I'll check out exec and eval. Also thinking I could just create a class attr dict that maps the strings to the imported functions. Commented May 10, 2017 at 19:12
  • @juanpa.arrivillaga I'm not passing the function directly b/c I don't have the caller import the functions, but rather they are imported where the class is defined. Are you suggesting this is bad (or nonpythonic)? Commented May 10, 2017 at 19:13

1 Answer 1

2

You could use a white list... or in this case, a "white dict"

class Whatever(object):

    allowed = { 'fizz':fizz, 'buzz':buz }

    def __init__(self, func_name='fizz'):
        try:
            self.func = self.allowed[func_name]
        except KeyError:
            print "Bad func_name"
            raise
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this is what I mentioned in the comments above as a decent alternative.

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.