0

I want to do something like this:

def a():
  # do stuff
  return stuff

def b():
  # do stuff
  return different_stuff

def c():
  # do one last thing
  return 200

for func in this_file:
  print func_name
  print func_return_value

I essentially want to mimic this flask app, without the flask parts:

app = Flask(__name__)
app.register_blueprint(my_bp, url_prefix='/test')
my_bp.data = fake_data

def tests():
  with app.test_client() as c:
    for rule in app.url_map.iter_rules():
      if len(rule.arguments) == 0 and 'GET' in rule.methods:
        resp = c.get(rule.rule)
        log.debug(resp)
        log.debug(resp.data)

is this possible?

3 Answers 3

3

Like this:

import sys

# some functions...
def a():
   return 'a'

def b():
   return 'b'

def c():
   return 'c'

# get the module object for this file    
module = sys.modules[__name__]

# get a list of the names that are in this module  
for name in dir(module):
   # get the Python object from this module with the given name
   obj = getattr(module, name)
   # ...and if it's callable (a function), call it.
   if callable(obj):
      print obj()

running this gives:

bgporter@varese ~/temp:python moduleTest.py
a
b
c

Note that the functions will not necessarily be called in the order of definition as they are here.

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

Comments

1

Use this code to create the python module get_module_attrs.py

import sys
module = __import__(sys.argv[1])
for name in dir(module):
   obj = getattr(module, name)
   if callable(obj):
      print obj.__name__

Then you can call it as $python get_module_attrs.py <name_of_module>

Enjoy it!!

Comments

1

Maybe:

def a(): return 1
def b(): return 2
def c(): return 3

for f in globals ().values ():
    if callable (f): continue
    print f.__name__
    print f ()

1 Comment

use callable(f) to determine if f can be called. cf. docs.python.org/2.7/library/functions.html#callable

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.