Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Code quality fixes for grass package (lib/python) #576

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 18 additions & 10 deletions lib/python/.flake8
Original file line number Diff line number Diff line change
@@ -1,24 +1,19 @@
[flake8]
ignore =
E262, # inline comment should start with '# '
E265, # block comment should start with '# '
E266, # too many leading '#' for block comment
E402, # module level import not at top of file
E502, # the backslash is redundant between brackets
E711, # comparison to None should be 'if cond is None:'
E712, # comparison to True should be 'if cond is True:' or 'if cond:'
E721, # do not compare types, use 'isinstance()'
E722, # do not use bare 'except'
E731, # do not assign a lambda expression, use a def
E741, # ambiguous variable name 'l'
F401, # '.reader.BandReferenceReader' imported but unused
F403, # 'from ctypes import *' used; unable to detect undefined names
F405, # 'RasterRow' may be undefined, or defined from star imports: ctypes, grass.pygrass.raster, grass.pygrass.vector
F811, # redefinition of unused 'utils' from line 26
F821, # undefined name '_'
F841, # local variable 't0' is assigned to but never used
F901, # 'raise NotImplemented' should be 'raise NotImplementedError'
W605, # invalid escape sequence '\_'
E262, # inline comment should start with '# '
E265, # block comment should start with '# '
E266, # too many leading '#' for block comment
F821, # undefined name '_'
E502, # the backslash is redundant between brackets
W291, # trailing whitespace
W292, # no newline at end of file
W293, # blank line contains whitespace
Expand Down Expand Up @@ -57,6 +52,19 @@ ignore =
E305, # expected 2 blank lines after class or function definition, found 1
E401, # multiple imports on one line

per-file-ignores =
# C wrappers call libgis.G_gisinit before importing other modules.
# TODO: Is this really needed?
pygrass/vector/__init__.py: E402,
pygrass/raster/__init__.py: E402,
pygrass/utils.py: E402,
# Current benchmarks/tests are changing sys.path before import.
# Possibly, a different approach should be taken there anyway.
pygrass/tests/benchmark.py: E402,
# Configuration file for Sphinx:
# Ignoring import/code mix and line length.
docs/conf.py: E402, E501

max-line-length = 88
exclude =
.git,
Expand Down
2 changes: 1 addition & 1 deletion lib/python/ctypes/ctypesgencore/parser/cgrammar.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
from . import yacc


if sys.version_info.major == 3:
if sys.version_info.major >= 3:
long = int


Expand Down
2 changes: 1 addition & 1 deletion lib/python/ctypes/ctypesgencore/parser/pplexer.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@


PY2 = True
if sys.version_info.major == 3:
if sys.version_info.major >= 3:
PY2 = False
long = int

Expand Down
3 changes: 1 addition & 2 deletions lib/python/gunittest/checkers.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import sys
import re
import doctest
import hashlib

from grass.script.utils import decode, encode, _get_encoding

Expand Down Expand Up @@ -555,8 +556,6 @@ def check_text_ellipsis_doctest(reference, actual):
optionflags=doctest.ELLIPSIS)


import hashlib

# optimal size depends on file system and maybe on hasher.block_size
_BUFFER_SIZE = 2**16

Expand Down
14 changes: 7 additions & 7 deletions lib/python/gunittest/multireport.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,17 +18,17 @@
import operator
from collections import defaultdict, namedtuple


# TODO: we should be able to work without matplotlib
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.dates import date2num

from grass.gunittest.checkers import text_to_keyvalue
from grass.gunittest.utils import ensure_dir
from grass.gunittest.reporters import success_to_html_percent

# TODO: we should be able to work without matplotlib
import matplotlib
matplotlib.use('Agg')
# This counts as code already, so silence "import not at top of file".
# Perhaps in the future, switch_backend() could be used.
import matplotlib.pyplot as plt # noqa: E402
from matplotlib.dates import date2num # noqa: E402

class TestResultSummary(object):
def __init__(self):
Expand Down
2 changes: 1 addition & 1 deletion lib/python/imaging/images2swf.py
Original file line number Diff line number Diff line change
Expand Up @@ -425,7 +425,7 @@ def __init__(self):

def ProcessTag(self):
""" Implement this to create the tag. """
raise NotImplemented()
raise NotImplementedError()

def GetTag(self):
""" Calls processTag and attaches the header. """
Expand Down
5 changes: 4 additions & 1 deletion lib/python/pygrass/modules/grid/grid.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,12 +169,15 @@ def copy_groups(groups, gisrc_src, gisrc_dst, region=None):
:returns: None

"""

def rmloc(r):
return r.split('@')[0] if '@' in r else r

env = os.environ.copy()
# instantiate modules
get_grp = Module('i.group', flags='lg', stdout_=sub.PIPE, run_=False)
set_grp = Module('i.group')
get_grp.run_ = True
rmloc = lambda r: r.split('@')[0] if '@' in r else r

src = read_gisrc(gisrc_src)
dst = read_gisrc(gisrc_dst)
Expand Down
2 changes: 1 addition & 1 deletion lib/python/pygrass/raster/abstract.py
Original file line number Diff line number Diff line change
Expand Up @@ -527,7 +527,7 @@ def get_value(self, point, region=None):
:param point: pair of coordinates in tuple object or class object with coords() method
"""
# Check for tuple
if type(point) != type([]) and type(point) != type(()):
if not isinstance(point, list) and not isinstance(point, tuple):
point = point.coords()

if not region:
Expand Down
3 changes: 1 addition & 2 deletions lib/python/pygrass/rpc/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
import grass.lib.gis as libgis
from .base import RPCServerBase
from grass.pygrass.gis.region import Region
import grass.pygrass.utils as utils
from grass.pygrass import utils
import logging

###############################################################################
Expand Down Expand Up @@ -434,7 +434,6 @@ def get_vector_features_as_wkb_list(self, name, mapset=None, extent=None,

if __name__ == "__main__":
import doctest
from grass.pygrass import utils
from grass.pygrass.modules import Module
Module("g.region", n=40, s=0, e=40, w=0, res=10)
Module("r.mapcalc", expression="%s = row() + (10 * col())"%(test_raster_name),
Expand Down
1 change: 0 additions & 1 deletion lib/python/pygrass/vector/abstract.py
Original file line number Diff line number Diff line change
Expand Up @@ -443,6 +443,5 @@ def build(self):

if __name__ == "__main__":
import doctest
from grass.pygrass import utils
utils.create_test_vector_map(test_vector_name)
doctest.testmod()
10 changes: 6 additions & 4 deletions lib/python/pygrass/vector/table.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,6 @@
import os
import sys

if sys.version_info.major == 3:
long = int
unicode = str

import ctypes
import numpy as np
from sqlite3 import OperationalError
Expand All @@ -34,6 +30,12 @@
from grass.pygrass.vector import sql
from grass.lib.ctypes_preamble import String


if sys.version_info.major >= 3:
long = int
unicode = str


# For test purposes
test_vector_name = "table_doctest_map"

Expand Down
2 changes: 1 addition & 1 deletion lib/python/pygrass/vector/testsuite/test_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
from grass.pygrass.vector.table import Table, get_path


if sys.version_info.major == 3:
if sys.version_info.major >= 3:
long = int

# dictionary that generate random data
Expand Down
7 changes: 4 additions & 3 deletions lib/python/script/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
from grass.exceptions import ScriptError, CalledModuleError

# PY2/PY3 compat
if sys.version_info.major > 2:
if sys.version_info.major >= 3:
unicode = str

# subprocess wrapper that uses shell on Windows
Expand Down Expand Up @@ -224,8 +224,9 @@ def _access_check(fn, mode):
return name
return None

if sys.version_info.major > 2:
shutil_which = shutil.which
if sys.version_info.major >= 3:
# Use shutil.which in Python 3, not the custom implementation.
shutil_which = shutil.which # noqa: F811

# Added because of scripts calling scripts on MS Windows.
# Module name (here cmd) differs from the file name (does not have extension).
Expand Down
2 changes: 1 addition & 1 deletion lib/python/script/raster.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
from .utils import float_or_dms, parse_key_val, try_remove


if sys.version_info.major == 3:
if sys.version_info.major >= 3:
unicode = str


Expand Down
10 changes: 6 additions & 4 deletions lib/python/script/task.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,9 @@
import sys
import string

if sys.version_info.major == 3:
unicode = str
from .utils import encode, decode, split
from .core import *


try:
import xml.etree.ElementTree as etree
Expand All @@ -36,8 +37,9 @@
else:
ETREE_EXCEPTIONS = (expat.ExpatError)

from .utils import encode, decode, split
from .core import *

if sys.version_info.major >= 3:
unicode = str


class grassTask:
Expand Down
11 changes: 8 additions & 3 deletions lib/python/script/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
import time


if sys.version_info.major == 3:
if sys.version_info.major >= 3:
unicode = str


Expand Down Expand Up @@ -334,8 +334,13 @@ def split(s):
def natural_sort(l):
"""Returns sorted strings using natural sort
"""
convert = lambda text: int(text) if text.isdigit() else text.lower()
alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]

def convert(text):
return int(text) if text.isdigit() else text.lower()

def alphanum_key(key):
return [convert(c) for c in re.split('([0-9]+)', key)]

return sorted(l, key=alphanum_key)


Expand Down
6 changes: 3 additions & 3 deletions lib/python/temporal/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,6 @@
import sys
import grass.script as gscript

if sys.version_info.major == 3:
long = int

from .c_libraries_interface import *
from grass.pygrass import messages
from grass.script.utils import decode, encode
Expand All @@ -55,6 +52,9 @@
import atexit
from datetime import datetime

if sys.version_info.major >= 3:
long = int

###############################################################################


Expand Down
2 changes: 1 addition & 1 deletion lib/python/temporal/space_time_datasets.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
STRDSRelativeTime, STR3DSAbsoluteTime, STR3DSRelativeTime, STVDSAbsoluteTime, STVDSRelativeTime
import grass.script.array as garray
from .core import init
from datetime import datetime


###############################################################################

Expand Down