Skip to content Skip to sidebar Skip to footer

Python: Import Module Without Executing Script

I looked at a similar question but it does not really answer the question that I have. Say I have the following code (overly simplified to highlight only my question). class A:

Solution 1:

This answer is just to demonstrate that it can be done, but would obviously need a better solution to ensure you are including the class(es) you want to include.

>>>code = ast.parse(open("someones_class.py").read())>>>code.body.pop(1)
<_ast.Assign object at 0x108c82450>
>>>code.body.pop(1)
<_ast.Print object at 0x108c82590>
>>>eval(compile(code, '', 'exec'))>>>test = A(4)>>>test
<__main__.A instance at 0x108c7df80>

You could inspect the code body for the elements you want to include and remove the rest.

NOTE: This is a giant hack.

Solution 2:

Nope, there's no way to prevent those extra lines from being executed. The best you can do is read the script and parse out the class -- using that to create the class you want.

This is likely way more work than you want to do, but, for the strong willed, the ast module might be helpful.

Solution 3:

No, there's no way. At least not without extreme trickery... that is to say, pretty much everything is possible in Python if you are willing to hack some weird "solution".

Where does that "someones_class.py" come from? Why can't you change it? I mean, edit the file, not change it from your code. Can you tell the person who wrote it not to write sort-a test code at top level?

There's an interesting (and kinda important) lesson about Python hidden here: that "class A:" is not a declaration. It's actually code that the Python interpreter executes when loading the file.

Post a Comment for "Python: Import Module Without Executing Script"