Regex to catch code that uses private members in python, unless its a function def
--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Flying Over Ancient Lands
--
Chapters
00:00 Regex To Catch Code That Uses Private Members In Python, Unless Its A Function Def
01:07 Accepted Answer Score 2
01:18 Answer 2 Score 1
02:05 Thank you
--
Full question
https://stackoverflow.com/questions/3625...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #regex #python27
#avk47
    Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Flying Over Ancient Lands
--
Chapters
00:00 Regex To Catch Code That Uses Private Members In Python, Unless Its A Function Def
01:07 Accepted Answer Score 2
01:18 Answer 2 Score 1
02:05 Thank you
--
Full question
https://stackoverflow.com/questions/3625...
--
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.