'Dynamic' class instances

Eric Jacobs x at x.x
Wed Oct 27 21:03:10 EDT 1999


Ken Power wrote:
> 
> Hmmm. Thank you for the input. I really appreciate it. If you would
> please, in a simple example, how would you, "use a  dictionary for the
> purpose rather than manipulating any namespaces."?
> 
> The part about namespaces I understand (should the new instance be
> global in nature, or localized to a module), using dictionaries in
> your implied sense, I do not understand, please expound.

I can only speculate about what you need to do here, but taking
from your original example:


class spam:
   pass

test = raw_input("class name: ")
test = spam()


What I assume you're trying to do is take whatever that user enters
here, create a variable with that name, and put a new instance of
the spam class in it. So:

class name: happy

would result in a variable named happy that contains a new instance
of spam. But consider what would happen if they entered:

class name: sys

or even

class name: spam

Python wouldn't issue an error in this case; it would simply
happily overwrite the variables sys and spam with an instance
of spam. The latter case could effectively delete the spam
class, replacing it with one of its instances!

A dictionary would be better suited:

d = {}
test = raw_input("class name: ")
d[test] = spam()

Now if they type "happy", you have a variable that you can
access via d["happy"]. If they type "sys", you can use
d["sys"], etc, and there's no chance of the user interfering
with the execution of your module.

Suppose you wanted to do the opposite thing: have the user
enter the name of class which is to be instantiated. So:

class name: Pickler

would create an instance of the class Pickler. A dictionary
would also help here:

d = {"Pickler": Pickler, "Unpickler": Unpickler}
test = raw_input("class name: ")
instance = d[test]()

By listing out the dictionary items by hand, you can
strictly control what the user may and may not access at
your prompt.




More information about the Python-list mailing list