0

I have already seen:

... and based on that, I made this example:

#!/usr/bin/env python3

import sys, os
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *

import inspect

# https://stackoverflow.com/q/18907712 ; https://stackoverflow.com/q/34439
def get_this_file_functions():
  funclist = []
  for name, obj in inspect.getmembers(sys.modules[__name__]):
    if inspect.isfunction(obj):
      funclist.append(name)
    elif inspect.isclass(obj):
      for attrname, attr in inspect.getmembers(obj):
        if inspect.ismethod(getattr(obj, attrname, None)):
          funclist.append(attrname)
  return funclist


class MyMainWindow(QMainWindow):
  def __init__(self):
    super(MyMainWindow, self).__init__()
    self.init_GUI() # NB: Blocks, because of self.show()!

  def init_GUI(self):
    self.setGeometry(50, 50, 850, 650)
    self.setWindowTitle("Window Title")
    print("get_this_file_functions:\n{}".format(get_this_file_functions()))
    self.show() # blocks


################################ MAIN
if __name__== '__main__':
  app = QApplication(sys.argv)
  myGUI = MyMainWindow()
  sys.exit(app.exec_())

... however, when I run this, all I get printed is:

get_this_file_functions:
['get_this_file_functions']

... that is - I don't get MyMainWindow.__init__ nor MyMainWindow.init_GUI.

So, how can I get all functions defined in a file - including all defined class methods?

1

1 Answer 1

2

On Python 3, calling inspect.ismethod on an attribute of a class that happens to be a function will always be False, because it will just be a plain function. function.__get__ only returns a method object when accessed as an attribute of an instance.

If you want to get all "methods" of the class just use inspect.isfunction.

>>> class A:
...     def __init__(self): pass
... 
>>> A.__init__
<function A.__init__ at 0x7fd524dd2f80>
>>> inspect.ismethod(A.__init__)
False
>>> inspect.isfunction(A.__init__)
True
>>> inspect.ismethod(A().__init__)
True
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, inspect.isfunction works great!

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.