Casie Bao


All the lights we cannot see


Python tricks

Folder Structure Best Practice

README.rst
LICENSE
setup.py
requirements.txt
sample/
    __init__.py
    core.py
    helpers.py
docs/
    conf.py
    index.rst
tests/
    test_basic.py
    test_advanced.py
notebooks/
  • reStructuredText(.rst) is a file format for textual data used primarily in the Python programming language community for technical documentation.

List files and folders in the current directory

import os
arr = os.listdir("<dir to work on>")
print(arr) => ['3ebooks.txt', 'documents']

arguments

For a function def example(a,b, c=None, r="w", d=[], *ae, **ab), the correct order of defining parameters are:

  1. positional paramter or non-default parameter (e.g., a,b)
  2. keyword parameter or default parameter (e.g., r="w", d=[])
  3. keyword-only parameter (e.g., *args)
  4. var-keyword parameter (e.g., **kwargs)

Static method

  • Static methods are methods that are bound to a class rather than its object. They do not require a class instance creation.
class Dates:
    def __init__(self, date):
        self.date = date
        
    def getDate(self):
        return self.date

    @staticmethod
    def toDashDate(date):
        return date.replace("/", "-")

date = Dates("15-12-2016")
dateFromDB = "15/12/2016"
dateWithDash = Dates.toDashDate(dateFromDB)

if(date.getDate() == dateWithDash):
    print("Equal")
else:
    print("Unequal")

# output "Equal"
  • note in the above example, users don’t need to create an object of the class Date, it can use its static method by directly calling <classname>.<static method name>.
  • It is a static method because it doesn’t need to access any properties of Dates itself (e.g., “self”) and only requires the parameters.
  • We can also create toDashDate outside the class, but since it works only for dates, it’s logical to keep it inside the Dates class.
Latest Articles

Python argparse and namespace

What is argparse?The Python argparse module defines what arguments it requires, and argparse will figure out how to parse those out of sys.argv. It also automatically generates help and usage messa...…

Read More
Eariler Articles

Python Modules

What is a Python egg?A Python egg is a structure embodying the release of a specific version of a Python module, comprising its code, resources and metadata. It needs to be importable and discovera...…

Read More