0

I have a requirement where I need to parse the functions defined in a python file from another python file.

e.g. I have a python file with following contents:

a.py

import os, sys

def function1('text'):
   pass
def function2('text'):
   pass

Another file is: b.py

interested_func = 'function2'

function_list = <code to fetch the functions defined in a.py>
if interested_func in function_list:
   print 'match found'

How can I get the functions from a.py into b.py so that I can compare the same with the 'interested_func' data and can do specific task based on the match.

Please note that I have 100s of files with different functions defined inside them, so I do not want to import the file.

Please help, thanks in advance!

5
  • 1
    import, dir, and callable are your friends Commented May 16, 2017 at 18:15
  • Hi Dan, I cannot import the file as I have 100 of such files (similar to a.py) and each file having their own set of functions. Commented May 16, 2017 at 18:17
  • 1
    @AMANDEEPSINGH Why can't you import them? Of course you can import them. Commented May 16, 2017 at 18:20
  • @juanpa.arrivillaga, I have shared a snippet of the code which I am writing, In my real application, the module to parse (in this case a.py) is stored in a variable (say module = 'a'). In similar way, with each iteration of my code, the variable changes and the python file to parse also changes, can you please suggest me here.. Commented May 16, 2017 at 18:24
  • You can import all the required files and then process them as and when you need to call something from a specific file? Commented May 16, 2017 at 18:30

1 Answer 1

1

You should probably use the importlib module:

import importlib

obj = importlib.import_module(module)
print(dir(obj))

You can read more about importlib over in the Python docs.

If that doesn't work for you, then you'll probably want to look at some static code analysis tools such as pylint that might give you a clue into how to do this sort of thing. Another place to look would be to check out PyDev's source code and see how it does code analysis.

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

Comments

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.