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?

3
  • 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. Commented Jul 18, 2015 at 2:35
  • stackoverflow.com/questions/8552165/… Commented Jul 18, 2015 at 2: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. Commented Jul 18, 2015 at 2:51

1 Answer 1

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?

Sign up to request clarification or add additional context in comments.

3 Comments

thx. I'll try to use a different way to analyze source codes.
This isn't entirely True, you can use the ast to extract some data from a module without executing: stackoverflow.com/questions/42875156
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.