3

Given a python file, I want to find out all of the scopes and declarations for the identifiers in the file.

For example, given this file:

import a
from b import xyz

def my_func(g):
   print "2"

my_func(0)
a.function_in_a(3)
xyz(4)

I want the output to be:

  • on line 7, my_func refers to my_func defined in line 4 of this file
  • on line 8, a refers to the module a. function_in_a refers to the function defined in module a
  • on line 9, xyz refers to the function defined in module b

Is there a library that does this for me? Basically I'm trying to use the in the context of IDE functionality / code autocomplete / understanding scopes of variables. Basically, I'm interested in understanding the location of an identifier's (variable, function, etc) definition, much like how an IDE like PyCharm determines it.

oxuser
  • 1,257
  • 2
  • 16
  • 23
  • There are no declarations in Python only definitions (name bindings). If a name doesn't refer to an object; it is NameError/UnboundLocalError. Look at jedi, rope libraries though Python is too dynamic to get the answer in all cases. – jfs Aug 15 '15 at 21:23
  • A package like flake8 figures this stuff out; at a lower level you can use the AST. – Patrick Maupin Aug 16 '15 at 03:47

1 Answers1

2

Strange that I haven't seen this issue before.

There's jedi.names, which would do pretty much what you want!

https://jedi.readthedocs.io/en/latest/docs/api.html#jedi.names

thinwybk
  • 4,193
  • 2
  • 40
  • 76
Dave Halter
  • 15,556
  • 13
  • 76
  • 103