Question about importlib

Frank Millman frank at chagford.com
Sun Mar 8 03:30:25 EDT 2015


Hi all

It is well known that if you import a module more than once, the overhead 
for the subsequent imports is negligible.

Does anyone happen to know if the same is true of the following?

        module_name, func_name = func_name.rsplit('.', 1)
        module = importlib.import_module(module_name)
        getattr(module, func_name)(caller, xml_elem)

I have a situation where I want to call a function dynamically, by passing a 
string containing a path to the function. The same function could be called 
multiple times. I would hope that the overhead for the second and subsequent 
calls is also fairly minimal.

Actually, as I write this, I realise that there is a more important question 
that had not occurred to me before. Is this a potential security risk? My 
intention is that the caller would only call functions within my own 
modules, but this could be used to call any arbitrary function.

You cannot pass arbitrary arguments to the function. The arguments are the 
'caller', which can only be an object within my application, and an xml 
element, from which the function can extract attributes using 
xml_elem.get(attr_name).

Before posting this I ran some timing tests, and the overhead does indeed 
seem to be minimal - 0.0001 sec on a slow desktop machine.

I think it is still worth posting, for any insights into either question.

Thanks

Frank Millman






More information about the Python-list mailing list