call of non-function (type string) error

Paul Prescod paulp at ActiveState.com
Tue Apr 10 20:49:41 EDT 2001


Graham Guttocks wrote:
> 
> Greetings,
> 
> Any suggestions on how to get around this problem?  I'm trying to call
> a function using variables, but it obviously doesn't work that way.
> 
> -----------------------------------------------
> 
> CIPHER = "DES3"
> exec "from Crypto.Cipher import %s" % CIPHER
> 
> # cipherobj = DES3.new(KEY, DES3.CBC, IV)
> cipherobj = CIPHER + 'new'(KEY,CIPHER + '.CBC',IV)

Strings and exec are hardly ever necessary. They should be buried deep
in a module somewhere. Use getattr instead:

What you want is

CIPHER = "DES"
import Crypto.Cipher

cipher = getattr(Cyrpto.Cipher, CIPHER)
cipherobj = cipher.new(KEY, CIPHER+".CBC", IV)

-- 
Take a recipe. Leave a recipe.  
Python Cookbook!  http://www.ActiveState.com/pythoncookbook




More information about the Python-list mailing list