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?

sdbbs
  • 4,270
  • 5
  • 32
  • 87
  • 1
    Does this answer your question? [How do I get list of methods in a Python class?](https://stackoverflow.com/questions/1911281/how-do-i-get-list-of-methods-in-a-python-class) – Jean-Louis Mbaka Nov 27 '20 at 12:15

1 Answers1

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
Iguananaut
  • 21,810
  • 5
  • 50
  • 63