Skip to content

Instantly share code, notes, and snippets.

@mightymercado
Last active March 26, 2020 07:10
Show Gist options
  • Save mightymercado/d90a21161666e28a6d4ae52db6fe735b to your computer and use it in GitHub Desktop.
Save mightymercado/d90a21161666e28a6d4ae52db6fe735b to your computer and use it in GitHub Desktop.
Refactoring Todo

Syntax Refactoring

It is advised to use PEP 8 Style Guide.

  1. Python uses snake case variables by default.
  2. Line length should be at most 79. Use \ to break up a line.
    one, two, three, four, five, size, seven, eight, nine, \
        ten, eleven = token.split()
  3. Some files should be broken down into more files because they are too long (e.g. flask/app/utils.py).

Data Structures

  1. Use list instead of dictionary when the index is an integer. It's a more pythonic approach.
    browsers = []
    for i in range(N):
        browsers.append(Browser())
    OR
    browsers = [None] * N
    for i in range(N):
        browsers[i] = Browser()
    OR better yet
    browsers = [Browser() for i in range(N)]
  2. Use dictionaries as switches instead of if-else.
    mapping = {
        'main': 'Main Item',
        'testrun': 'Testrun',
        'testcase_sequence': 'Test Case Sequence',
        'teststep_sequence': 'test_step'
    }
    
    if item_type in mapping:
        return mapping[item_type]
    
    return ''
  3. Use enums for constants.
    from enum import Enum
    class Color(Enum):
        RED = 1
        GREEN = 2
        BLUE = 3
  4. Use data classes. AddressCreate.py seems like a good candidate. Could also be a good alternative to having dynamic **kwargs argument.

Documentation Improvements

  1. Complete type hinting in function arguments and return.
from typing import List, Optional

def func(a: int, b: string, c: Optional[int] = None) -> List[int]:
    ret = [a, b]
    if c:
        ret.append(c)
    return ret

Misc.

  1. Use with syntax to automatically file even on exception. This is already being used, but some parts still use f.close()
    with open(...) as f:
      pass
  2. Parsing and converting code is bit hacky with many .replace() calls. Maybe try a formal approach with a parser, then work on the syntax tree.

API Best Practices

  1. Use Marshmallow to serialize SQL schemas into JSON.
  2. Database calls should be abstracted away from the controllers in views.py.
  3. Use Flask Blueprints to make a subroute for each item_type.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment