According to ChatGPT, this is why coding conventions are important:
Coding conventions may seem like a bunch of arbitrary rules that some grumpy programmers made up to ruin your day. But fear not, for these conventions are actually your allies in the wild world of coding!
Picture this: coding conventions are like a secret handshake among developers, a universal language that helps us understand each other's code without pulling our hair out.
They bring order to the chaos, like traffic rules that prevent cars from turning into bumper cars. So, embrace these guidelines, my friend, and let them be your compass in the vast coding landscape. They'll save you from countless hours of debugging, make your code more readable, and ensure that even your future self will thank you.
Trust me, coding conventions are not just rules, they're your passport to becoming a coding rockstar! Now, go forth and conquer the code with style and panache!
So I guess it's okay if we have a few guidelines. The Google Python Style Guide is a very good reference, and here's the gist of it:
Code layout
- Limit line length to 80 characters, when possible.
- Use spaces around operators and after commas.
- Add a space before inline comments.
- Use
is
andis not
for identity comparison, not==
and!=
.
Naming conventions
- Use descriptive names for variables, functions, and modules.
- Use
lowercase
letters with underscores for module names. - Use
CapWords
(capitalized words with no underscores) for class names. - Use lowercase letters with underscores for function and variable names.
- Avoid using single lowercase letters, except for simple counters or iterators.
Comments and documentation
- Use comments to explain complex code.
- Use docstrings to document modules, classes, and functions.
- Follow the "Google Style" for docstrings (reStructuredText format).
Testing
As much as possible, we should write automatic tests for our code using pytest
Tests should be located in a tests
directory, at the root of your repository. In this directory, create a file for each module of your package, name following the convention test_modulename.py
.
For example, your project structure could be like this:
example-repo/
┣ qimex/
┃ ┣ __init__.py
┃ ┗ examples.py
┣ tests/
┃ ┣ __init__.py
┃ ┗ test_examples.py
┣ .gitignore
┣ LICENSE
┗ README.md
Inside examples.py
you could have this function:
def say_hello(user):
greeting = (f'Hello {user}!')
return greeting
This function simply receives a string and returns another string greeting the user.
A test_examples.py
should contain the test for it:
def test_say_hello():
expected_output = "Hello Alice!"
result = qimex.examples.say_hello("Alice")
assert result == expected_output
This is simply running the function and checking if the result is as expected.
To run all the tests, navigate to the root of your project and run pytest
. Everything inside the tests
folder will be executed, and a report will be shown.