Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to catch code that uses private members in python, unless its a function def

I'm trying to write a regex to catch any use of private members in python, with the exception of function names.

For example, the following should return true:

a = __something__
b.__something()
__bla = 5
a[__bla__]
... etc etc

But the following should return false:

def __unicode__(self):
    ....

(because it has the "def" before it)

I wrote this expression:

regexp = re.compile(r'(?!def\s)[^a-zA-Z^_\s]__[a-zA-Z]')

And it works for most cases, but for some reason it always return false if there's a space before the private, eg this will not return true:

regexp.search("something = __private")

What am I doing wrong here? the "(?!def\s)" should not match if have "def " before it, and I handle spaces before the two underscores, eg inside "[^a-zA-Z^_\s]". so why isn't it working?

EDIT:

While the accepted answer is correct for regex, I recommend looking at Padraic Cunningham's answer for a better solution using ast. Thanks,

like image 919
Ronen Ness Avatar asked Mar 01 '26 21:03

Ronen Ness


1 Answers

You could try :

(?<!def\s)(\b__[a-zA-Z])

Example

source

like image 110
Till Avatar answered Mar 04 '26 10:03

Till



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!