Python Best Practices
Structure
- docs/
- module/
- tests/
- LICENSE
- README.md
- requirements.txt - readme for requiremeents like modules
- setup.py - distutils builds and distribute modules
requirements.txtβ
pip3 install -r requirements.txt
Naming Conventions- Variables: this_is_a_variable
- Classes: CapWords
- protected methods: _single_leading_underscore
- private methods: __double_leading_underscore
- constants: CAPS_WITH_UNDERSCORES
- 4 spaces indentation
External Libraries:
Testingβ
Noseβ
To get started with nose2
, install nose2
from PyPI and execute it on the command line. nose2
will try to discover all test scripts named test*.py
and test cases inheriting from unittest.TestCase
in your current directory:
$ pip install nose2
$ python -m nose2
Internalβ
New file: test_sum_unittest.py
import unittest
class TestSum(unittest.TestCase):
def test_sum(self):
self.assertEqual(sum([1, 2, 3]), 6, "Should be 6")
def test_sum_tuple(self):
self.assertEqual(sum((1, 2, 2)), 6, "Should be 6")
if __name__ == '__main__':
unittest.main()
Main Modules:β
https://www.guru99.com/learn-python-main-function-with-examples-understand-main.html
def main():
print("hello world!")
if __name__ == "__main__":
main()
print("Guru99")
print("Value in built variable name is: ",__name__)
Self and init
https://micropyramid.com/blog/understand-self-and-__init__-method-in-python-class/
def __init__(self, model, color, company, speed_limit):
self.color = color
self.company = company
self.speed_limit = speed_limit
self.model = model
def start(self):
print("started")
Package manager
brew install pyenv