1

I'm trying to do something similar with: Load module from string in python

Sometimes I read source code provided by the user:

module = imp.new_module('AppModule')
exec_(s, module.__dict__)
sys.modules['AppModule'] = module
return module

And sometimes import from a file

module = __import__(module_name, fromlist=_fromlist)
return module

These modules are loaded to map objects and it'll be used inside a IDE.

My problem is: If there is any method call outside if __name__ == '__main__': this code is being executed and can interact with the IDE.

How can I import modules ignoring methods from being executed?

Community
  • 1
  • 1
Aron Bordin
  • 436
  • 4
  • 13
  • I am not understanding exactly your problem, but remember that when you import module, you are basically importing all the code from that file (if it is a file), and if you have some methods (that you call) or some global code there, they will be executed. To avoid this, simply remove all global code, or any call to some function, and just call them from your main file when you need. – nbro Jul 18 '15 at 02:35
  • http://stackoverflow.com/questions/8552165/importing-a-python-module-without-actually-executing-it – Paul Rooney Jul 18 '15 at 02:35
  • Everything defined in the module, including functions, classes, global variables, are the result of executing the statements that define them. This also applies recursively to everything defined in a class. – Ross Ridge Jul 18 '15 at 02:51

1 Answers1

1

The process of importing a module requires that its code be executed. The interpreter creates a new namespace and populates it by executing the module's code with the new namespace as the global namespace, after which you can access those values (remember that the def and class statements are executable).

So maybe you will have to educate your users not to write modules that interact with the IDE?

holdenweb
  • 33,305
  • 7
  • 57
  • 77
  • thx. I'll try to use a different way to analyze source codes. – Aron Bordin Jul 18 '15 at 14:48
  • This isn't entirely True, you can use the `ast` to extract *some* data from a module without executing: http://stackoverflow.com/questions/42875156 – ideasman42 Mar 18 '17 at 14:34
  • Perhaps I was interpreting "How can I import modules ignoring methods from being executed?" too literally. But I'm sure your approach could make for an interesting answer. Of course we shouldn't forget that `def` and `class` are executable statements, so "importing without execution" wouldn't be very helpful. – holdenweb Mar 24 '17 at 14:57