5

I'm making a program that detects python files and reads their classes and functions for then to be called. How do I list the functions from another python file without importing it? and how do I call them?

Structure of the program:

  • Index.py (main py file)
  • /Content
    • /Modules
      • Modules.py
      • ChickenModule.py (module I want to get functions from)

Modules.py list all the python files from /Modules and stores them on a list. Index.py calls the functions in Modules.py (Just to keep things less messy)

ChickenModule.py has a Class named ChickenStuff that prints "I'm a chicken" whenever it's self.(something) called.

The goal of the program is for the user to be able to put .py files in modules and when running index.py the functions and classes of said .py files will be listed.

8
  • 5
    Why do you want to do this without importing them? That would be the standard approach. Commented Jul 19, 2019 at 23:15
  • The goal of the program is to be able to put files into the Modules folder and the program to automatically read them. Commented Jul 19, 2019 at 23:17
  • 4
    import is the facility Python has defined for obtaining services and attributes from another module. Why do you need to find another way to accomplish this? import is how the program automatically reads them. Commented Jul 19, 2019 at 23:18
  • 1
    You're going to have to import them somehow to use what's defined in them. Commented Jul 19, 2019 at 23:18
  • 1
    If that doesn't solve your problem, it's worth expanding on why in the question (you can always edit it). Right now the question doesn't make much sense, unfortunately. Commented Jul 19, 2019 at 23:22

1 Answer 1

4

There's a built in library called importlib that might be what you need. I'm assuming that you want classes listed. You'll need inspect for this.

import os
import os.path as path
import importlib
import inspect

# get a list of all files in Content/Modules
filelist = os.listdir("Content/Modules")

# import every file ending in .py
for fname in filelist:
  if path.splitext(fname)[1] == 'py':
    my_module = importlib.import_module(path.splitext(fname)[0]) # load the module
    for _, obj in inspect.getmembers(my_module): # iterate through members
      if isinstance(obj, type): # check if members is a class
        print(obj)
Sign up to request clarification or add additional context in comments.

3 Comments

"You'll need inspect for this." no you don't. In python 3, simply isinstance(obj, type)
What if I want to list functions too?
@BigXKu use if isinstance(obj, type) or isinstance(obj, function): instead

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.