How to get a list of all non imported names in a Python module? -


given module containing :

import stuff foo import foo bar import *  cst = true  def func(): pass 

how can define function get_defined_objects can do:

print(get_defined_objects('path.to.module')) {'cst': true, 'func', <function path.to.module.func>} 

right solution can imagine read original module file, extract defined names re.search(r'^(?:def|class )?(\w+)(?:\s*=)?' import module, , find intersection __dict__.

is there cleaner ?

here start using ast. note code not cover possible cases, although should handle e.g. multiple assignment properly. consider investigating ast's data structures , api more closely if access compiled code, example.

import ast  open('module.py') f:     data = f.read()     tree = ast.parse(data)     elements = [el el in tree.body if type(el) in (ast.assign, ast.functiondef, ast.classdef)]  result = {}  el in elements:     if type(el) == ast.assign:         t in el.targets:             if type(el.value) == ast.call:                 result[t.id] = el.value.func.id + '()'             else:                 attr in ['id', 'i', 's']:                     try:                         result[t.id] = getattr(el.value, attr)                         break                     except exception e:                         pass     elif type(el) == ast.functiondef:         result[el.name] = '<function %s>' % el.name     else:         result[el.name] = '<class %s>' % el.name  print result # 

Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -