Skip to content

Commit

Permalink
feat: add ruff and codespell integration (#35)
Browse files Browse the repository at this point in the history
  • Loading branch information
XuehaiPan authored Apr 4, 2023
1 parent d0e9fcc commit 65206b2
Show file tree
Hide file tree
Showing 60 changed files with 426 additions and 255 deletions.
4 changes: 4 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,10 @@ jobs:
run: |
make pre-commit
- name: ruff
run: |
make ruff
- name: flake8
run: |
make flake8
Expand Down
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,9 @@ venv.bak/
# mkdocs documentation
/site

# ruff
.ruff_cache/

# mypy
.mypy_cache/
.dmypy.json
Expand Down
23 changes: 17 additions & 6 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@
ci:
skip: [pylint]
autofix_prs: true
autofix_commit_msg: "fix: [pre-commit.ci] auto fixes [...]"
autoupdate_commit_msg: "chore(pre-commit): [pre-commit.ci] autoupdate"
autofix_commit_msg: 'fix: [pre-commit.ci] auto fixes [...]'
autoupdate_commit_msg: 'chore(pre-commit): [pre-commit.ci] autoupdate'
default_stages: [commit, push, manual]
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0
Expand All @@ -23,22 +24,24 @@ repos:
- id: detect-private-key
- id: debug-statements
- id: double-quote-string-fixer
- repo: https://github.com/charliermarsh/ruff-pre-commit
rev: v0.0.259
hooks:
- id: ruff
args: [--fix, --exit-non-zero-on-fix]
- repo: https://github.com/PyCQA/isort
rev: 5.12.0
hooks:
- id: isort
stages: [commit, push, manual]
- repo: https://github.com/psf/black
rev: 23.1.0
hooks:
- id: black-jupyter
stages: [commit, push, manual]
- repo: https://github.com/asottile/pyupgrade
rev: v3.3.1
hooks:
- id: pyupgrade
args: [--py38-plus] # sync with requires-python
stages: [commit, push, manual]
exclude: |
(?x)(
^examples/
Expand All @@ -59,6 +62,15 @@ repos:
^tests/|
^docs/conf.py$
)
- repo: https://github.com/codespell-project/codespell
rev: v2.2.4
hooks:
- id: codespell
additional_dependencies: [".[toml]"]
exclude: |
(?x)(
^docs/spelling_wordlist.txt$
)
- repo: local
hooks:
- id: pylint
Expand All @@ -67,7 +79,6 @@ repos:
language: system
types: [python]
require_serial: true
stages: [commit, push, manual]
exclude: |
(?x)(
^examples/|
Expand Down
15 changes: 13 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,9 @@ py-format-install:
$(call check_pip_install,isort)
$(call check_pip_install_extra,black,black[jupyter])

ruff-install:
$(call check_pip_install,ruff)

mypy-install:
$(call check_pip_install,mypy)

Expand Down Expand Up @@ -104,6 +107,12 @@ py-format: py-format-install
$(PYTHON) -m isort --project $(PROJECT_NAME) --check $(PYTHON_FILES) && \
$(PYTHON) -m black --check $(PYTHON_FILES)

ruff: ruff-install
$(PYTHON) -m ruff check .

ruff-fix: ruff-install
$(PYTHON) -m ruff check . --fix --exit-non-zero-on-fix

mypy: mypy-install
$(PYTHON) -m mypy $(PROJECT_PATH)

Expand Down Expand Up @@ -133,16 +142,18 @@ clean-docs:

# TODO: add mypy when ready
# TODO: add docstyle when ready
lint: flake8 py-format pylint addlicense spelling
lint: ruff flake8 py-format pylint addlicense spelling

format: py-format-install addlicense-install
format: py-format-install ruff-install addlicense-install
$(PYTHON) -m isort --project $(PROJECT_NAME) $(PYTHON_FILES)
$(PYTHON) -m black $(PYTHON_FILES)
$(PYTHON) -m ruff check . --fix --exit-zero
addlicense -c $(COPYRIGHT) -ignore tests/coverage.xml -l apache -y 2022 $(SOURCE_FOLDERS)

clean-py:
find . -type f -name '*.py[co]' -delete
find . -depth -type d -name "__pycache__" -exec rm -r "{}" +
find . -depth -type d -name ".ruff_cache" -exec rm -r "{}" +
find . -depth -type d -name ".mypy_cache" -exec rm -r "{}" +
find . -depth -type d -name ".pytest_cache" -exec rm -r "{}" +
rm tests/.coverage
Expand Down
17 changes: 8 additions & 9 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,8 @@

# -- Project information -----------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information
import os
import pathlib
import sys
from typing import Any, Dict


ROOT_DIR = pathlib.Path(__file__).absolute().parent.parent.parent
Expand Down Expand Up @@ -58,13 +56,14 @@
html_baseurl = 'https://safety_gymnasium.com'
html_copy_source = False
# html_favicon = '_static/images/favicon.png'
html_context: Dict[str, Any] = {}
html_context['conf_py_path'] = '/docs/'
html_context['display_github'] = False
html_context['github_user'] = 'PKU-MARL'
html_context['github_repo'] = 'Safety Gymnasium'
html_context['github_version'] = 'main'
html_context['slug'] = 'safety gymnasium'
html_context = {
'conf_py_path': '/docs/',
'display_github': False,
'github_user': 'PKU-MARL',
'github_repo': 'Safety Gymnasium',
'github_version': 'main',
'slug': 'safety gymnasium',
}

html_static_path = ['_static']
html_css_files = []
Expand Down
2 changes: 1 addition & 1 deletion docs/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ Safety Gymnasium is a standard API for safe reinforcement learning, and a divers

.. toctree::
:hidden:
:caption: COMPONETS OF ENVIRONMENTS
:caption: COMPONENTS OF ENVIRONMENTS

components_of_environments/agents
components_of_environments/objects
Expand Down
3 changes: 0 additions & 3 deletions examples/env.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,6 @@ def run_random(env_name):
assert env.observation_space.contains(obs)
act = env.action_space.sample()
assert env.action_space.contains(act)
# Use the environment's built_in max_episode_steps
if hasattr(env, '_max_episode_steps'): # pylint: disable=unused-variable
max_ep_len = env._max_episode_steps # pylint: disable=unused-variable,protected-access
# pylint: disable-next=unused-variable
obs, reward, cost, terminated, truncated, info = env.step(act)

Expand Down
5 changes: 1 addition & 4 deletions examples/vision_env.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def run_random(env_name):
terminated, truncated = False, False
ep_ret, ep_cost = 0, 0
render_list = []
for i in range(1001): # pylint: disable=unused-variable
for _i in range(1001): # pylint: disable=unused-variable
if terminated or truncated:
print(f'Episode Return: {ep_ret} \t Episode Cost: {ep_cost}')
ep_ret, ep_cost = 0, 0
Expand All @@ -49,9 +49,6 @@ def run_random(env_name):
assert env.observation_space.contains(obs)
act = env.action_space.sample()
assert env.action_space.contains(act)
# Use the environment's built_in max_episode_steps
if hasattr(env, '_max_episode_steps'): # pylint: disable=protected-access
max_ep_len = env._max_episode_steps # pylint: disable=unused-variable,protected-access
render_list.append(obs['vision'])
# pylint: disable-next=unused-variable
obs, reward, cost, terminated, truncated, info = env.step(act)
Expand Down
78 changes: 78 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -108,3 +108,81 @@ convention = "google"

[tool.doc8]
max-line-length = 500

[tool.codespell]
ignore-words = "docs/spelling_wordlist.txt"

[tool.ruff]
# Sync with requires-python
target-version = "py38"
line-length = 100
show-source = true
src = ["omnisafe", "tests", "examples"]
select = [
"E", "W", # pycodestyle
"F", # pyflakes
"UP", # pyupgrade
"ANN", # flake8-annotations
"S", # flake8-bandit
"BLE", # flake8-blind-except
"B", # flake8-bugbear
"COM", # flake8-commas
"C4", # flake8-comprehensions
"EXE", # flake8-executable
"ISC", # flake8-implicit-str-concat
"PIE", # flake8-pie
"PYI", # flake8-pyi
"Q", # flake8-quotes
"RSE", # flake8-raise
"RET", # flake8-return
"SIM", # flake8-simplify
"TID", # flake8-tidy-imports
"RUF", # ruff
]
ignore = [
# E501: line too long
# W505: doc line too long
# too long docstring due to long example blocks
"E501",
"W505",
# TODO: Remove this five ignores
# ANN001: missing type annotation for function argument
# ANN002: missing type annotation for `*args`
# ANN003: missing type annotation for `**kwargs`
# ANN201: missing return type annotation for public function
# ANN202: missing return type annotation for private function
"ANN001","ANN002","ANN003","ANN201","ANN202",
# ANN101: missing type annotation for `self` in method
# ANN102: missing type annotation for `cls` in classmethod
"ANN101",
"ANN102",
# ANN401: dynamically typed expressions (typing.Any) are disallowed
"ANN401",
# S101: use of `assert` detected
# internal use and may never raise at runtime
"S101",
# PLR0402: use from {module} import {name} in lieu of alias
# use alias for import convention (e.g., `import torch.nn as nn`)
"PLR0402",
]

[tool.ruff.per-file-ignores]
"__init__.py" = [
"F401", # unused-import
]
"tests/**/*.py" = [
"ANN", # flake8-annotations
"S", # flake8-bandit
"BLE", # flake8-blind-except
]

[tool.ruff.flake8-annotations]
allow-star-arg-any = true

[tool.ruff.flake8-quotes]
docstring-quotes = "double"
multiline-quotes = "double"
inline-quotes = "single"

[tool.ruff.flake8-tidy-imports]
ban-relative-imports = "all"
9 changes: 7 additions & 2 deletions safety_gymnasium/agents/ant.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,14 @@ def __init__( # pylint: disable=too-many-arguments
locations: list = None,
keepout: float = 0.4,
rot: float = None,
):
) -> None:
super().__init__(
self.__class__.__name__, random_generator, placements, locations, keepout, rot
self.__class__.__name__,
random_generator,
placements,
locations,
keepout,
rot,
)

def is_alive(self):
Expand Down
9 changes: 7 additions & 2 deletions safety_gymnasium/agents/car.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,14 @@ def __init__( # pylint: disable=too-many-arguments
locations: list = None,
keepout: float = 0.4,
rot: float = None,
):
) -> None:
super().__init__(
self.__class__.__name__, random_generator, placements, locations, keepout, rot
self.__class__.__name__,
random_generator,
placements,
locations,
keepout,
rot,
)

def is_alive(self):
Expand Down
9 changes: 7 additions & 2 deletions safety_gymnasium/agents/point.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,14 @@ def __init__( # pylint: disable=too-many-arguments
locations: list = None,
keepout: float = 0.4,
rot: float = None,
):
) -> None:
super().__init__(
self.__class__.__name__, random_generator, placements, locations, keepout, rot
self.__class__.__name__,
random_generator,
placements,
locations,
keepout,
rot,
)

def is_alive(self):
Expand Down
9 changes: 7 additions & 2 deletions safety_gymnasium/agents/racecar.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,14 @@ def __init__( # pylint: disable=too-many-arguments
locations: list = None,
keepout: float = 0.4,
rot: float = None,
):
) -> None:
super().__init__(
self.__class__.__name__, random_generator, placements, locations, keepout, rot
self.__class__.__name__,
random_generator,
placements,
locations,
keepout,
rot,
)

def is_alive(self):
Expand Down
3 changes: 1 addition & 2 deletions safety_gymnasium/assets/free_geoms/push_box.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ class PushBox(FreeGeom): # pylint: disable=too-many-instance-attributes

def get_config(self, xy_pos, rot):
"""To facilitate get specific config for this object."""
obj = {
return {
'name': 'push_box',
'type': 'box',
'size': np.ones(3) * self.size,
Expand All @@ -56,7 +56,6 @@ def get_config(self, xy_pos, rot):
'group': self.group,
'rgba': self.color,
}
return obj

def _specific_agent_config(self):
"""Modify the push_box property according to specific agent."""
Expand Down
Loading

0 comments on commit 65206b2

Please sign in to comment.