Is python getattr good to use?

I create a shell environment. My original method of handling user input was to use dictionary matching commands (strings) for methods of different classes, using the fact that functions are first class objects in python.

For more flexibility (mainly for parsing commands) I'm going to change my setting to use the getattr (command) command to grab the method I need and then pass arguments to it at the end of my parsing. Another advantage of this approach is the lack of having to update my (currently statically implemented) command dictionary every time I add a new method / command.

My question is double. First, does getattr have the same problems as eval? Secondly, will I hit the effectiveness of my shell? It doesn't matter how many methods / commands I have? I am currently scrolling through 30 teams that could double in the long run.

+7
performance python shell getattr
source share
2 answers

The difference between direct access to attributes and using getattr () should be pretty minor. You can determine the difference between the bytecodes of the two versions using the Python dis module to compare the two approaches:

 >>> import dis >>> dis.dis(lambda x: x.foo) 1 0 LOAD_FAST 0 (x) 3 LOAD_ATTR 0 (foo) 6 RETURN_VALUE >>> dis.dis(lambda x: getattr(x, 'foo')) 1 0 LOAD_GLOBAL 0 (getattr) 3 LOAD_FAST 0 (x) 6 LOAD_CONST 0 ('foo') 9 CALL_FUNCTION 2 12 RETURN_VALUE 

This, however, sounds like you are developing a shell that is very similar to the way the cmd Python library executes the command line command line. cmd allows you to create shells that execute commands by matching the command name with the function defined on the cmd.Cmd object, for example:

 import cmd class EchoCmd(cmd.Cmd): """Simple command processor example.""" def do_echo(self, line): print line def do_EOF(self, line): return True if __name__ == '__main__': EchoCmd().cmdloop() 

You can read more about the module in the documentation or at http://www.doughellmann.com/PyMOTW/cmd/index.html

+20
source share

does getattr have the same problems as eval?

No - code using eval() terribly annoying to support and can have serious security issues. Calling getattr(x, "foo") is another way to write x.foo .

I will take a hit on the effectiveness of my shell

It will be imperceptibly slower if the command is not found, but not enough to make a difference. You would only notice this when running tests with tens of thousands of records.

+6
source share

All Articles