I've written a fair bit of my first significant Python script. I just finished reading PEP 8, and I learned that lower_case_with_underscores is preferred for instance variable names. I've been using mixedCase for variable names throughout, and I'd like my code to be make more Pythonic by changing those to lower_case_with_underscores if that's how we do things around here.
I could probably write some script that searches for mixedCase and tries to smartly replace it, but before I potentially reinvent the wheel, my question is whether a solution for that already exists, either within a Python-savvy editor or as a standalone application; or whether there's another approach that would accomplish the task of converting all mixedCase variable names to lower_case_with_underscores. I have searched a fair bit for a solution but didn't turn up anything. Any technique that specifically would yield this result would be appreciated.
I was able to accomplish what I wanted using GNU sed:
sed -i -e :loop -re 's/(^|[^A-Za-z_])([a-z0-9_]+)([A-Z])([A-Za-z0-9_]*)'\
'([^A-Za-z0-9_]|$)/\1\2_\l\3\4\5/' -e 't loop' myFile.py
It finds every instance of mixedCase -- but not CapitalWords, so class names are left intact -- and replaces it with lower_case_with_underscores; e.g. myVariable becomes my_variable, but MyClass remains MyClass.
(On an unrelated note, now that I've done it, I think I prefer the appearance of mixedCase over lower_case_with_underscores. The appearance of so many underscores all over my code is weird. But I'll do things the Python Way and see if I get used to it, particularly if I intend for my code to be seen or worked with by others; or maybe I'll do it the way I like and I've now got a simple way of converting it to the PEP 8 way if I intend to make the code public.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With