Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: import module without executing script

Tags:

python

import

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:
    def __init__(self,x):
        self.val = x

a = A(4)
print a.val

This code resides in a file someones_class.py. I now want to import and use class A in my program without modifying someones_class.py. If I do from someones_class import A, python would still execute the script lines in the file.

Question: Is there a way to just import class A without the last two lines getting executed?

I know about if __name__ == '__main__' thing but I do not have the option of modifying someones_class.py file as it is obtained only after my program starts executing.

like image 253
Nik Avatar asked Dec 15 '22 11:12

Nik


2 Answers

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.

like image 190
sberry Avatar answered Dec 18 '22 10:12

sberry


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.

like image 23
mgilson Avatar answered Dec 18 '22 11:12

mgilson