redefining a function through assignment

Terry Hancock hancock at anansispaceworks.com
Fri Sep 9 09:21:46 EDT 2005


On Thursday 08 September 2005 06:56 pm, Daniel Britt wrote:
> This will print out 'new method'. If any other instance of mod1.test is 
> created calling func1, func1 will always reference the newFunc function. 
> This is less than desirable to say the least.

Well, actually it's very desireable, but I'm sorry it surprised you. ;-)

ISTM, you're just discovering that functions are "first-class objects"
in Python.  That's going to be the expectation of anyone familiar with
programming in the language.

> Is there any way of preventing 
> this from ever happening? I searched around for quite a while and I haven't 
> been able to find anyone who has a solution. 

Please don't try to delete this functionality -- you will cause equally
unpleasant surprises for anyone trying to use your package.

> The reason I am asking this is 
> b/c I want to build an application in python that has plugins. I want to 
> make sure that a programmer could not accidently or intentionally clobber 
> over another plugins code, which they could easily do. Any help would be 
> appreciated. Thanks

The solution is to keep each plugin in its own namespace.

More protection than that shouldn't be attempted. Even if a plugin
does manage to clobber another plugin's code, it won't be unintentional.
You don't know what that programmer is attempting to do. You can always
regard the plugin as "broken" or "dangerous" or "noncompliant" if it
does this sort of thing and document the point.

But how can you be sure there isn't a good reason for it if the plugin
author feels it was necessary?

It's very unlikely that they will do anything of the sort if you just
keep each plugin module in it's own namespace (which basically means
not using any "from plugin_mod import *" but rather "import plugin_mod").

This approach has worked for me in the past.

HTH,
Terry

--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com




More information about the Python-list mailing list