Source

pycode / sourceindex / parser.py

import inspect


def parse_dynamic(module_name):

	def parse_scope(obj, scope):
		
		def parse_args(obj, lineno, scope):
			argspec = inspect.getargspec(obj)
			for arg in argspec.args:
				yield ("argument", ".".join(scope), arg, lineno)
		
		def findsource(obj):
			try:
				code, lineno = inspect.findsource(obj)
			except IOError:
				code = lineno = ""
			except TypeError:
				code = lineno = ""
			return code, lineno
	
		doc = inspect.getdoc(obj) or inspect.getcomments(obj)
		for (name, member) in inspect.getmembers(obj):
			if inspect.isfunction(member):
				code, lineno = findsource(member)
				yield ("func", ".".join(scope), name, lineno)
				for result in parse_args(member, lineno, scope + [name]):
					yield result
			elif inspect.isclass(member) and  member.__module__ == scope[0]:
				code, lineno = findsource(member)
				yield ("class", ".".join(scope), name, lineno)
				for result in parse_scope(member, scope + [name]):
					yield result
			elif inspect.ismethod(member):
				code, lineno = findsource(member)
				yield ("method", ".".join(scope), name, lineno)
				for result in parse_args(member, lineno, scope + [name]):
					yield result
	
	mod = __import__(module_name, {}, {}, ["foobardoesnotexist"])
	for result in parse_scope(mod, [mod.__name__]):
		yield result
	


parse = parse_dynamic



if __name__ == "__main__":
	for item in parse("string"):
		print item