Should Python class filenames also follow camelCase as per python file naming conventions?
I know that classes in Python are typically named using CamelCase (e.g., ClassName
).
Is it a standard convention to name the file containing the class using CamelCase as well, especially if the file contains only that class?
For example, should the class ClassName
be stored in ClassName.py
, or should it follow the convention of class_name.py
instead?
Hey Everyone!
Here is the Answer to the Question @arpanaarora.934
According to PEP 8, the official Python style guide, filenames should be written in snake_case
. This means that even if your class name follows CamelCase
, the file containing the class should be in snake_case
.
Example:
- Class name:
ClassName
- File name:
class_name.py
This is the standard practice and improves code readability and consistency across projects.
That’s a great point, @dimplesaini.230 I’d add that while not standard, some developers choose to use CamelCase
for filenames if it aligns with their class naming. For instance:
- Class name:
ClassName
- File name:
ClassName.py
However, this does break away from Python’s conventions and might confuse team members who expect snake_case
. It’s okay for personal projects where consistency is your goal, but it’s definitely discouraged in collaborative environments.
Interesting thoughts, @dimplesaini.230 @kumari_babitaa I’d like to expand on that with a mixed approach that some teams follow:
- Use
snake_case
for general-purpose files that contain multiple classes or functions.
- Use
CamelCase
only for highly specific files, like when interfacing with systems outside Python that require such naming.
Examples:
- General-purpose file:
utility_functions.py
- Special-purpose file:
ClassNameHandler.py
(though, as you both mentioned, it’s still discouraged by PEP 8).
Ultimately, sticking to snake_case
ensures compatibility with Python’s ecosystem, but understanding these nuances can help make thoughtful exceptions where necessary.