Skip to content

Instantly share code, notes, and snippets.

@twolfson
Last active May 18, 2016 09:16
Show Gist options
  • Save twolfson/f5bb3996011a45fc4da5 to your computer and use it in GitHub Desktop.
Save twolfson/f5bb3996011a45fc4da5 to your computer and use it in GitHub Desktop.
Proof of concept to require trailing commas in `flake8`
*.pyc
build/
dist/
flake8_commas.egg-info
flake8_commas/

We are interested in supporting trailing commas via flake8 but need to verify that this can be easily achieved via AST tokens. This repo is a proof of concept for said verification.

Conclusion: It can be done via tokens but it will be complicated since there is no distinction of brackets.

https://hg.python.org/cpython/file/2.7/Lib/tokenize.py#l87

hello = {
'world': True
}
# Load in dependencies
import ast
# Define our linter
class CommaLinter(object):
"""Flake8 extension to lint for/against trailing commas"""
# TODO: Can we really support `disallow` as well?
name = 'flake8_commas'
# TODO: Figure out good foundry versioning system...
version = '1.0.0'
_code = 'C902'
def __init__(self, tree, filename):
"""Handle incoming AST and filename"""
# Save filename for later
self.filename = filename
def run(self):
"""Walk through the tree and find any multiline params/tuples/lists/dicts without a trailing comma"""
# Walk our AST
# https://docs.python.org/2/library/token.html
# https://hg.python.org/cpython/file/2.7/Lib/tokenize.py
for node in ast.walk(self.tree):
# If we are on a dict
# TODO: Handle params, tuples, lists, and dicts
if isinstance(node, ast.Dict):
# DEV: We allow ourselves to keep on walking as there might be nested dicts
# TODO: What's a store/load?
print node.__dict__
return []
#!/usr/bin/env bash
# Echo commands and exit on first error
set -e
set -x
# Create a folder to install with
mkdir flake8_commas
ln -s ../flake8_commas.py flake8_commas/__init__.py
# Install our dependencies
pip install -r requirements.txt
# Load our module
python setup.py develop
from setuptools import setup, find_packages
setup(
name='flake8_commas',
version='1.0.0',
description='Flake8 extension to lint for/against trailing commas',
# long_description=open('README.rst').read(),
keywords=[
],
author='Todd Wolfson',
author_email='todd@twolfson.com',
url='',
download_url='none/archive/master.zip',
packages=find_packages(),
license='UNLICENSE',
install_requires=open('requirements.txt').readlines(),
entry_points={
# TODO: Figure out valid extension number
'flake8.extension': ['C902 = flake8_commas:CommaLinter'],
},
# https://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: Public Domain',
'Operating System :: OS Independent',
'Programming Language :: Python'
]
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment