# -*- coding: utf-8 -*-"""Example Google style docstrings.This module demonstrates documentation as specified by the `Google PythonStyle Guide`_. Docstrings may extend over multiple lines. Sections are createdwith a section header and a colon followed by a block of indented text.Example: Examples can be given using either the ``Example`` or ``Examples`` sections. Sections support any reStructuredText formatting, including literal blocks:: $ python example_google.pySection breaks are created by resuming unindented text. Section breaksare also implicitly created anytime a new section starts.Attributes: module_level_variable1 (int): Module level variables may be documented in either the ``Attributes`` section of the module docstring, or in an inline docstring immediately following the variable. Either form is acceptable, but the two should not be mixed. Choose one convention to document module level variables and be consistent with it.Todo: * For module TODOs * You have to also use ``sphinx.ext.todo`` extension.. _Google Python Style Guide: http://google.github.io/styleguide/pyguide.html"""
Example function Docstring
"""Connects to the next available port. Args: (int) minimum: A port value greater or equal to 1024. Returns: (int) The new minimum port. Raises: ConnectionError: If no available port is found."""
virtualenv
# installingpipinstallvirtualenv# installing with specific python versionpython3.8-mpipinstallbeautifulsoup4# creatingvirtualenvenv_name--python=python3.6# by default it'd be python2.7# activatesourceenv_name/bin/activate# deactivatedeactivate# savingpipfreeze>requirements.txt
import os, refrom dotenv import load_dotenv, find_dotenvdef__load_env(self,begin_pattern="CONTENT_MANAGER_ENV_*"):""" Env variables on system need to be stored beginning with begin_pattern if so, they will be stored in self.env dict """ env ={}load_dotenv(find_dotenv())for var in os.environ.keys():if re.match(begin_pattern,var): env[var[len(begin_pattern)-1:]]= os.getenv(var)iflen(env.keys())==0:returnNoneelse:return env
Confusion matrix
import numpy as npdefcompute_confusion_matrix(true,pred):'''Computes a confusion matrix using numpy for two np.arrays true and pred. Results are identical (and similar in computation time) to: "from sklearn.metrics import confusion_matrix" However, this function avoids the dependency on sklearn.''' K =len(np.unique(true))# Number of classes result = np.zeros((K, K))for i inrange(len(true)): result[true[i]][pred[i]] +=1return result
test = [[1,2], [3,4], [5,6]][[t[j]for t in test] for j inrange(len(test[0]))]
Get current time
from datetime import datetimenow = datetime.now()current_time = now.strftime("%Y%m%d%H%M")
Useful magic methods
__add__ , __repr__
Creating a package
having setup.py like:
from setuptools import setupsetup(name='pkg_name', version='0.1', description='Pkg description', packages=['pkg_name'], zip_safe=False)
and a module at pkg_name folder, execute
cdpkg_parent_dirpythonsetup.pysdistbdist_wheelpipinstalltwine# commands to upload to the pypi test repositorytwineupload--repository-urlhttps://test.pypi.org/legacy/dist/*pipinstall--index-urlhttps://test.pypi.org/simple/pkg_name# command to upload to the pypi repositorytwineuploaddist/*pipinstallpkg_name
Reminders
include a README file detailing the files in your package and how to install the package.
Comment your code - use docstrings and inline comments where appropriate.
Refactor code when possible - if you find your functions are getting too long, then refactor your code!
Use object-oriented programming whenever it makes sense to do so.
You're encouraged to write unit tests! The coding exercises in this lesson contained unit tests, so you can use those tests as a model for your package.
Use GitHub for version control, and commit your work often.
As a reminder, your package should be placed in a folder with the following folders and files:
a folder with the name of your package that contains: