-
Notifications
You must be signed in to change notification settings - Fork 14
How to Write Good Code
Luca edited this page Jan 30, 2024
·
10 revisions
Please adhere to this resource for the codestyle:
- Jupyter Notebook: All imports in first cell
- Python script: All imports in first line
- Absolute imports are recommended
from API import get_data
- Functions which should not be used outside the module scope
- Characterised by an underscore as the beginning of the function name
def _save_to_json(data, filename) -> None:
"""
This function saves data to a JSON file.
:param data: The data to be saved.
:param filename: The name of the file to save the data to.
:return: True if the data was successfully saved, False if not.
"""
with open(f"Data/{filename}", 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=4)
- Documented by docstrings
def get_user_repo(username: str) -> bool:
"""
This function gets the user's repository data from the GitHub API.
:param username: The username of the user.
:return: True if the request was successful, False if not.
"""
url: str = f"https://api.github.com/users/{username}/repos"
try:
response: requests.Response = requests.get(url)
response.raise_for_status() # This will raise an exception for HTTP error codes
repos_data: list = []
for repo in response.json():
repo_info: dict = {
'id': repo['id'],
'name': repo['name'],
}
repos_data.append(repo_info)
return True
- Use of inline comments should be separated by at least two spaces from the code statement, and they should not be used to point out the obvious
# Don't do this
x = x + 1 # Increment x
# Do this
x = x + 1 # Compensate for border