0

in answer to: Can Python print a function definition?

What's wrong with this?

# Get a list of all user-defined functions and print  their definitions
import inspect, sys, types
# sys.stdout.write(inspect.getsource(MyFunction))
#
print(sorted([f.__name__ for f in globals().values() if type(f) == types.FunctionType]))
print()
for f in globals().values():
    if type(f) == types.FunctionType:
         ## %pdef $f.__name__ is only the call signature 
        print(inspect.getsource(f))
  • 1
    "What's wrong with this?" *you* tell us. What output are you getting? What output were you *expecting*? Are you getting an error? What error. Post the full error message and the stack trace. Please see [ask] and the [help] – juanpa.arrivillaga Jan 20 '22 at 18:32
  • Thanks. It was working after a fashion, now no longer giving the mysterious `RuntimeError: dictionary changed size during iteration` diagnostic after the change. – BlipBertMon Feb 06 '22 at 21:14

1 Answers1

0

Based on this answer to 'Iterating through globals() dictionary', you can typecast your globals().values() to a list so that you can iterate on it without the error RuntimeError: dictionary changed size during iteration, which is presently what your code with for f in globals().values(): gives. Here's that change incorporated:

# Get a list of all user-defined functions and print  their definitions
import inspect, sys, types
# sys.stdout.write(inspect.getsource(MyFunction))
#
print(sorted([f.__name__ for f in globals().values() if type(f) == types.FunctionType]))
print()
for f in list(globals().values()):
    if type(f) == types.FunctionType:
         ## %pdef $f.__name__ is only the call signature 
        print(inspect.getsource(f))

The solution was found by running your code and seeing the error and then searching about errors iterating on globals. So in the future, it is suggested when posting to provide the error you see and what you expect as @juanpa.arrivillaga suggested. Also, please provide any steps you've already tried to fix it. In this case, you may have sorted it yourself by following that process as it was a direct substitution suggested. Granted, when learning it is often harder to understand what to search and how to effectively sort and implement those findings.

Wayne
  • 6,607
  • 8
  • 36
  • 93