Regex to catch code that uses private members in python, unless its a function def
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: RPG Blues Looping
--
Chapters
00:00 Question
01:34 Accepted answer (Score 2)
01:49 Answer 2 (Score 1)
02:52 Thank you
--
Full question
https://stackoverflow.com/questions/3625...
Accepted answer links:
[Example]: http://pythex.org/?rege
[source]: http://www.regular-expressions.info/look...
Answer 2 links:
[ast.NodeVisitor]: https://docs.python.org/2/library/ast.ht...
[here]: https://stackoverflow.com/questions/3019...
[greentreesnakes]: https://greentreesnakes.readthedocs.org/...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #regex #python27
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: RPG Blues Looping
--
Chapters
00:00 Question
01:34 Accepted answer (Score 2)
01:49 Answer 2 (Score 1)
02:52 Thank you
--
Full question
https://stackoverflow.com/questions/3625...
Accepted answer links:
[Example]: http://pythex.org/?rege
[source]: http://www.regular-expressions.info/look...
Answer 2 links:
[ast.NodeVisitor]: https://docs.python.org/2/library/ast.ht...
[here]: https://stackoverflow.com/questions/3019...
[greentreesnakes]: https://greentreesnakes.readthedocs.org/...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #regex #python27
#avk47
ACCEPTED ANSWER
Score 2
ANSWER 2
Score 1
Using ast.NodeVisitor it is very easy to get the attributes and a lot more reliable than a regex:
import inspect
import importlib
import ast
class FindAttr(ast.NodeVisitor):
def visit_Attribute(self, node):
print(node.attr)
mod = "test"
mod = importlib.import_module(mod)
p = ast.parse(inspect.getsource(mod))
f = FindAttr()
f.visit(p)
test.py:
class Foo(object):
def __init__(self):
self.__foo = "foo"
def meth1(self):
self.bar = "bar"
def meth2(self):
self.__foobar = "foobar"
def meth3(self):
self.blah = "foobar"
return self.blah
Output:
In [7]: mod = "test"
In [8]: mod = importlib.import_module(mod)
In [9]: p = ast.parse(inspect.getsource(mod))
In [10]: f = FindAttr()
In [11]: f.visit(p)
__foo
bar
__foobar
blah
All you need to so is check if node.attr.startswith("__") etc.. You can visit any nodes you like, FunctionDef, ClassDef like shown here, there is a comprehensive list of all the nodes in the greentreesnakes docs and their attributes.