Nitpick
Command-line tool and flake8 plugin to enforce the same settings across multiple language-independent projects.
Useful if you maintain multiple projects and are tired of copying/pasting the same INI/TOML/YAML/JSON keys and values over and over, in all of them.
The CLI now has a nitpick fix
command that modifies configuration files directly (pretty much like black and isort do with Python files).
See Command-line interface for more info.
Many more features are planned for the future, check the roadmap.
Note
This project is still a work in progress, so the API is not fully defined:
The style file syntax might have changes before the 1.0 stable release;
The numbers in the
NIP*
error codes might change; don’t fully rely on them;See also Breaking changes.
Quickstart
Install
Install in an isolated environment with pipx:
# Latest PyPI release
pipx install nitpick
# Development branch from GitHub
pipx install git+https://github.com/andreoliwa/nitpick
On macOS/Linux, install the latest release with Homebrew:
brew install andreoliwa/formulae/nitpick
# Development branch from GitHub
brew install andreoliwa/formulae/nitpick --HEAD
On Arch Linux, install with yay:
yay -Syu nitpick
Add to your project with Poetry:
poetry add --dev nitpick
Or install it with pip:
pip install -U nitpick
Run
To fix and modify your files directly:
nitpick fix
To check for errors only:
nitpick check
Nitpick is also a flake8 plugin, so you can run this on a project with at least one Python (.py
) file:
flake8 .
Nitpick will download and use the opinionated default style file.
You can use it as a template to Configure your own style.
Run as a pre-commit hook
If you use pre-commit on your project, add this to the .pre-commit-config.yaml
in your repository:
repos:
- repo: https://github.com/andreoliwa/nitpick
rev: v0.31.0
hooks:
- id: nitpick
There are 3 available hook IDs:
nitpick
andnitpick-fix
both run thenitpick fix
command;nitpick-check
runsnitpick check
.
If you want to run Nitpick as a flake8 plugin instead:
repos:
- repo: https://github.com/PyCQA/flake8
rev: 4.0.1
hooks:
- id: flake8
additional_dependencies: [nitpick]
To install the pre-commit
and commit-msg
Git hooks:
pre-commit install --install-hooks
pre-commit install -t commit-msg
To start checking all your code against the default rules:
pre-commit run --all-files
Modify files directly
Nitpick includes a CLI to apply your style and modify the configuration files directly:
nitpick fix
Read more details here: Command-line interface.
Styles
The style file
A “Nitpick code style” is a TOML file with the settings that should be present in config files from other tools.
Example of a style:
["pyproject.toml".tool.black]
line-length = 120
["pyproject.toml".tool.poetry.dev-dependencies]
pylint = "*"
["setup.cfg".flake8]
ignore = "D107,D202,D203,D401"
max-line-length = 120
inline-quotes = "double"
["setup.cfg".isort]
line_length = 120
multi_line_output = 3
include_trailing_comma = true
force_grid_wrap = 0
combine_as_imports = true
This example style will assert that:
Configure your own style
After creating your own TOML file with your style, add it to your pyproject.toml
file. See Configuration for details.
You can also check the style library, and use the styles to build your own.
Default search order for a style
A file or URL configured in the
pyproject.toml
file,[tool.nitpick]
section,style
key, as described in Configuration.Any nitpick-style.toml file found in the current directory (the one in which flake8 runs from) or above.
If no style is found, then the default style file from GitHub is used.
Style file syntax
A style file contains basically the configuration options you want to enforce in all your projects.
They are just the config to the tool, prefixed with the name of the config file.
E.g.: To configure the black formatter with a line length of 120, you use this in your pyproject.toml
:
[tool.black]
line-length = 120
To enforce that all your projects use this same line length, add this to your nitpick-style.toml file:
["pyproject.toml".tool.black]
line-length = 120
It’s the same exact section/key, just prefixed with the config file name ("pyproject.toml".
)
The same works for setup.cfg
.
To configure mypy to ignore missing imports in your project, this is needed on setup.cfg
:
[mypy]
ignore_missing_imports = true
To enforce all your projects to ignore missing imports, add this to your nitpick-style.toml file:
["setup.cfg".mypy]
ignore_missing_imports = true
Special configurations
Comparing elements on lists
Note
At the moment, this feature only works on :ref:`the YAML plugin <yamlplugin>`_.
On YAML files, a list (called a “sequence” in the YAML spec) can contain different elements:
Scalar values like int, float and string;
Dictionaries or objects with key/value pairs (called “mappings” in the YAML spec)
Other lists (sequences).
The default behaviour for all lists: when applying a style, Nitpick searches if the element already exists in the list; if not found, the element is appended at the end of list.
With scalar values, Nitpick compares the elements by their exact value. Strings are compared in a case-sensitive manner, and spaces are considered.
Dicts are compared by a “hash” of their key/value pairs.
On lists containing dicts, it is possible to define a custom “list key” used to search for an element, overriding the default compare mechanism above.
If an element is found by its key, the other key/values are compared and Nitpick applies the difference. If the key doesn’t exist, the new dict is appended at the end of the list.
Some files have a predefined configuration:
On
.pre-commit-config.yaml
, repos are searched by their hook IDs.On GitHub Workflow YAML files, steps are searched by their names.
You can define your own list keys for your YAML files (or override the predefined configs above) by using __list_keys
on your style:
["path/from/root/to/your/config.yaml".__list_keys]
"<list expression>" = "<search key expression>"
<list expression>
:
a dotted path to a list, e.g.
repos
,path.to.some.key
; ora pattern containing wildcards (
?
and*
). For example,jobs.*.steps
: alljobs
containingsteps
will use the same<search key expression>
.
<search key expression>
:
a key from the dict inside the list, e.g.
name
; ora parent key and its child key separated by a dot, e.g.
hooks.id
.
Warning
For now, only two-level nesting is possible: parent and child keys.
If you have suggestions for predefined list keys for other popular YAML files not covered by Nitpick (e.g.: GitLab CI config), feel free to create an issue or submit a pull request.
Breaking changes
Warning
Below are the breaking changes in the style before the API is stable. If your style was working in a previous version and now it’s not, check below.
missing_message
key was removed
missing_message
was removed. Use [nitpick.files.present]
now.
Before:
[nitpick.files."pyproject.toml"]
missing_message = "Install poetry and run 'poetry init' to create it"
Now:
[nitpick.files.present]
"pyproject.toml" = "Install poetry and run 'poetry init' to create it"
Configuration
The style file for your project should be configured in the [tool.nitpick]
section of the configuration file.
Possible configuration files (in order of precedence):
.nitpick.toml
pyproject.toml
The first file found will be used; the other files will be ignored.
Run the nipick init
CLI command to create a config file (init: Initialise a configuration file).
To configure your own style:
[tool.nitpick]
style = "/path/to/your-style-file.toml"
You can set style
with any local file or URL.
Remote style
Use the URL of the remote file.
If it’s hosted on GitHub, use any of the following formats:
GitHub URL scheme (github://
or gh://
) pinned to a specific version:
[tool.nitpick]
style = "github://andreoliwa/nitpick@v0.31.0/nitpick-style.toml"
# or
style = "gh://andreoliwa/nitpick@v0.31.0/nitpick-style.toml"
The @
syntax is used to get a Git reference (commit, tag, branch).
It is similar to the syntax used by pip
and pipx
:
If no Git reference is provided, the default GitHub branch will be used (for Nitpick, it’s develop
):
[tool.nitpick]
style = "github://andreoliwa/nitpick/nitpick-style.toml"
# or
style = "gh://andreoliwa/nitpick/nitpick-style.toml"
# It has the same effect as providing the default branch explicitly:
style = "github://andreoliwa/nitpick@develop/nitpick-style.toml"
# or
style = "gh://andreoliwa/nitpick@develop/nitpick-style.toml"
A regular GitHub URL also works. The corresponding raw URL will be used.
[tool.nitpick]
style = "https://github.com/andreoliwa/nitpick/blob/v0.31.0/nitpick-style.toml"
Or use the raw GitHub URL directly:
[tool.nitpick]
style = "https://raw.githubusercontent.com/andreoliwa/nitpick/v0.31.0/nitpick-style.toml"
You can also use the raw URL of a GitHub Gist:
[tool.nitpick]
style = "https://gist.githubusercontent.com/andreoliwa/f4fccf4e3e83a3228e8422c01a48be61/raw/ff3447bddfc5a8665538ddf9c250734e7a38eabb/remote-style.toml"
If your style is on a private GitHub repo, you can provide the token directly on the URL. Or you can use an environment variable to avoid keeping secrets in plain text.
[tool.nitpick]
# A literal token
style = "github://p5iCG5AJuDgY@some-user/a-private-repo@some-branch/nitpick-style.toml"
# Or reading the secret value from the MY_AUTH_KEY env var
style = "github://$MY_AUTH_KEY@some-user/a-private-repo@some-branch/nitpick-style.toml"
Note
A literal token cannot start with a $
.
All tokens must not contain any @
or :
characters.
Style inside Python package
The style file can be fetched from an installed Python package.
Example of a use case: you create a custom flake8 extension and you also want to distribute a (versioned) Nitpick style bundled as a resource inside the Python package (check out this issue: Get style file from python package · Issue #202).
Python package URL scheme is pypackage://
or py://
:
[tool.nitpick]
style = "pypackage://some_python_package.styles.nitpick-style.toml"
# or
style = "py://some_python_package.styles.nitpick-style.toml"
Thanks to @isac322 for this feature.
Cache
Remote styles can be cached to avoid unnecessary HTTP requests.
The cache can be configured with the cache
key; see the examples below.
By default, remote styles will be cached for one hour.
This default will also be used if the cache
key has an invalid value.
Expiring after a predefined time
The cache can be set to expire after a defined time unit.
Use the format cache = "<integer> <time unit>"
.
Time unit can be one of these (plural or singular, it doesn’t matter):
minutes
/minute
hours
/hour
days
/day
weeks
/week
To cache for 15 minutes:
[tool.nitpick]
style = "https://example.com/remote-style.toml"
cache = "15 minutes"
To cache for 1 day:
[tool.nitpick]
style = "https://example.com/remote-style.toml"
cache = "1 day"
Forever
With this option, once the style(s) are cached, they never expire.
[tool.nitpick]
style = "https://example.com/remote-style.toml"
cache = "forever"
Never
With this option, the cache is never used. The remote style file(s) are always looked-up and a HTTP request is always executed.
[tool.nitpick]
style = "https://example.com/remote-style.toml"
cache = "never"
Clearing
The cache files live in a subdirectory of your project: /path/to/your/project/.cache/nitpick/
.
To clear the cache, simply remove this directory.
Local style
Using a file in your home directory:
[tool.nitpick]
style = "~/some/path/to/another-style.toml"
Using a relative path from another project in your hard drive:
[tool.nitpick]
style = "../another-project/another-style.toml"
Multiple styles
You can also use multiple styles and mix local files and URLs.
Example of usage: the [tool.nitpick]
table on Nitpick’s own pyproject.toml.
[tool.nitpick]
style = [
"/path/to/first.toml",
"/another/path/to/second.toml",
"https://example.com/on/the/web/third.toml"
]
Note
The order is important: each style will override any keys that might be set by the previous .toml
file.
If a key is defined in more than one file, the value from the last file will prevail.
Override a remote style
You can use a remote style as a starting point, and override settings on your local style file.
Use ./
to indicate the local style:
[tool.nitpick]
style = [
"https://example.com/on/the/web/remote-style.toml",
"./my-local-style.toml",
]
For Windows users: even though the path separator is a backslash, use the example above as-is. The “dot-slash” is a convention for Nitpick to know this is a local style file.
Library (Presets)
If you want to configure your own style, those are the some styles you can reuse.
Many TOML configs below are used in the default style file.
You can use these examples directly with their py://
URL (see Multiple styles), or copy/paste the TOML into your own style file.
any
Style URL |
Description |
---|---|
javascript
Style URL |
Description |
---|---|
kotlin
Style URL |
Description |
---|---|
presets
Style URL |
Description |
---|---|
proto
Style URL |
Description |
---|---|
python
Style URL |
Description |
---|---|
Python 3.10 |
|
Python 3.7 |
|
Python 3.8 |
|
Python 3.9 |
|
Files that should not exist |
|
Current stable Python version |
|
shell
Style URL |
Description |
---|---|
The [nitpick] section
The [nitpick] section in the style file contains global settings for the style.
Those are settings that either don’t belong to any specific config file, or can be applied to all config files.
Minimum version
Show an upgrade message to the developer if Nitpick’s version is below minimum_version
:
[nitpick]
minimum_version = "0.10.0"
[nitpick.files]
Files that should exist
To enforce that certain files should exist in the project, you can add them to the style file as a dictionary of “file name” and “extra message”.
Use an empty string to not display any extra message.
[nitpick.files.present]
".editorconfig" = ""
"CHANGELOG.md" = "A project should have a changelog"
Files that should be deleted
To enforce that certain files should not exist in the project, you can add them to the style file.
[nitpick.files.absent]
"some_file.txt" = "This is an optional extra string to display after the warning"
"another_file.env" = ""
Multiple files can be configured as above. The message is optional.
Comma separated values
On setup.cfg
, some keys are lists of multiple values separated by commas, like flake8.ignore
.
On the style file, it’s possible to indicate which key/value pairs should be treated as multiple values instead of an exact string. Multiple keys can be added.
[nitpick.files."setup.cfg"]
comma_separated_values = ["flake8.ignore", "isort.some_key", "another_section.another_key"]
[nitpick.styles]
Styles can include other styles. Just provide a list of styles to include.
Example of usage: Nitpick’s default style.
[nitpick.styles]
include = ["styles/python37", "styles/poetry"]
The styles will be merged following the sequence in the list.
If a key/value pair appears in more than one sub-style, it will be overridden; the last declared key/pair will prevail.
Command-line interface
Note
The CLI is experimental, still under active development.
Nitpick has a CLI command to fix files automatically.
It doesn’t work for all the plugins yet. Currently, it works for:
INI files (like
setup.cfg
,tox.ini
,.editorconfig
,.pylintrc
, and any other.ini
)
It tries to preserve the comments and the formatting of the original file.
Some changes still have to be done manually; Nitpick cannot guess how to make certain changes automatically.
Run
nitpick fix
to modify files directly, ornitpick check
to only display the violations.The flake8 plugin only checks the files and doesn’t make changes. This is the default for now; once the CLI becomes more stable, the “fix mode” will become the default.
The output format aims to follow pycodestyle (pep8) default output format.
If you use Git, you can review the files before committing.
The available commands are described below.
Main options
Usage: nitpick [OPTIONS] COMMAND [ARGS]...
Enforce the same settings across multiple language-independent projects.
Options:
-p, --project DIRECTORY Path to project root
--offline Offline mode: no style will be downloaded (no HTTP
requests at all)
--version Show the version and exit.
--help Show this message and exit.
Commands:
check Don't modify files, just print the differences.
fix Fix files, modifying them directly.
init Create a [tool.nitpick] section in the configuration file if it...
ls List of files configured in the Nitpick style.
fix
: Modify files directly
At the end of execution, this command displays:
the number of fixed violations;
the number of violations that have to be changed manually.
Usage: nitpick fix [OPTIONS] [FILES]...
Fix files, modifying them directly.
You can use partial and multiple file names in the FILES argument.
Options:
-v, --verbose Increase logging verbosity (-v = INFO, -vv = DEBUG)
--help Show this message and exit.
check
: Don’t modify, just print the differences
Usage: nitpick check [OPTIONS] [FILES]...
Don't modify files, just print the differences.
Return code 0 means nothing would change. Return code 1 means some files
would be modified. You can use partial and multiple file names in the FILES
argument.
Options:
-v, --verbose Increase logging verbosity (-v = INFO, -vv = DEBUG)
--help Show this message and exit.
ls
: List configures files
Usage: nitpick ls [OPTIONS] [FILES]...
List of files configured in the Nitpick style.
Display existing files in green and absent files in red. You can use partial
and multiple file names in the FILES argument.
Options:
--help Show this message and exit.
init
: Initialise a configuration file
Usage: nitpick init [OPTIONS]
Create a [tool.nitpick] section in the configuration file if it doesn't
exist already.
Options:
--help Show this message and exit.
Note
Try running Nitpick with the new Command-line interface instead of a flake8 plugin.
In the future, there are plans to make flake8 an optional dependency.
Flake8 plugin
Nitpick is not a proper flake8 plugin; it piggybacks on flake8’s messaging system though.
Flake8 lints Python files; Nitpick “lints” configuration (text) files instead.
To act like a flake8 plugin, Nitpick does the following:
Use the first Python file found and ignore other Python files in the project.
Check the style file and compare with the configuration/text files.
Report violations on behalf of that Python file, and not on the configuration file that’s actually wrong.
So, if you have a violation on setup.cfg
, it will be reported like this:
./tasks.py:0:1: NIP323 File setup.cfg: [flake8]max-line-length is 80 but it should be like this:
[flake8]
max-line-length = 120
Notice the tasks.py
at the beginning of the line, and not setup.cfg
.
Note
To run Nitpick as a Flake8 plugin, the project must have at least one Python file*.
If your project is not a Python project, creating a dummy.py
file on the root of the project is enough.
Pre-commit hook and flake8
Currently, the default pre-commit hook uses flake8 in an unconventional and not recommended way.
flake8 --select=NIP
This current default pre-commit hook (called nitpick
) is a placeholder for the future, when flake8 will be only an optional dependency.
Why always_run: true
?
This in intentional, because Nitpick is not a conventional flake8 plugin.
Since flake8 only lints Python files, the pre-commit hook will only run when a Python file is modified. It won’t run when a config/text changes.
An example: suppose you’re using a remote Nitpick style (like the style from WeMake).
At the moment, their style currently checks setup.cfg
only.
Suppose they change or add an option on their isort.toml file.
If the nitpick pre-commit hook had always_run: false
and pass_filenames: true
, your local setup.cfg
would only be verified:
If a Python file was changed.
If you ran
pre-commit run --all-files
.
So basically the pre-commit hook would be useless to guarantee that your config files would always match the remote style… which is precisely the purpose of Nitpick.
Note
To avoid this, use the other pre-commit hooks, the ones that call the Nitpick CLI directly instead of running flake8
.
Root dir of the project
You should run Nitpick in the root dir of your project.
A directory is considered a root dir if it contains one of the following files:
Main Python file
On the root dir of the project Nitpick searches for a main Python file.
Every project must have at least one *.py
file, otherwise flake8 won’t even work.
Those are the Python files that are considered:
setup.py
app.py
andwsgi.py
(Flask CLI)autoapp.py
manage.py
any
*.py
file
Plugins
Nitpick uses plugins to handle configuration files.
There are plans to add plugins that handle certain file types, specific files, and user plugins. Check the roadmap.
Below are the currently included plugins.
INI files
Enforce configurations and autofix INI files.
Examples of .ini
files handled by this plugin:
Style examples enforcing values on INI files: flake8 configuration.
JSON files
Enforce configurations and autofix JSON files.
Add the configurations for the file name you wish to check. Style example: the default config for package.json.
Text files
Enforce configuration on text files.
To check if some.txt
file contains the lines abc
and def
(in any order):
[["some.txt".contains]]
line = "abc"
[["some.txt".contains]]
line = "def"
TOML files
Enforce configurations and autofix TOML files.
E.g.: pyproject.toml (PEP 518).
See also the [tool.poetry] section of the pyproject.toml file.
Style example: Python 3.8 version constraint. There are many other examples here.
YAML files
Enforce configurations and autofix YAML files.
Example: .pre-commit-config.yaml.
Style example: the default pre-commit hooks.
Warning
The plugin tries to preserve comments in the YAML file by using the ruamel.yaml
package.
It works for most cases.
If your comment was removed, place them in a different place of the fil and try again.
If it still doesn’t work, please report a bug.
Known issue: lists like args
and additional_dependencies
might be joined in a single line,
and comments between items will be removed.
Move your comments outside these lists, and they should be preserved.
Note
No validation of .pre-commit-config.yaml
will be done anymore in this generic YAML plugin.
Nitpick will not validate hooks and missing keys as it did before; it’s not the purpose of this package.
Troubleshooting
Crash on multi-threading
On macOS, flake8 might raise this error when calling requests.get(url)
:
objc[93329]: +[__NSPlaceholderDate initialize] may have been in progress in another thread when fork() was called.
objc[93329]: +[__NSPlaceholderDate initialize] may have been in progress in another thread when fork() was called. We cannot safely call it or ignore it in the fork() child process. Crashing instead. Set a breakpoint on objc_initializeAfterForkError to debug.
To solve this issue, add this environment variable to .bashrc
(or the initialization file for your favorite shell):
export OBJC_DISABLE_INITIALIZE_FORK_SAFETY=YES
Thanks to this StackOverflow answer.
ModuleNotFoundError: No module named ‘nitpick.plugins.XXX’
When upgrading to new versions, old plugins might be renamed in setuptools entry points.
But they might still be present in the entry_points.txt plugin metadata in your virtualenv.
$ rg nitpick.plugins.setup ~/Library/Caches/pypoetry/
/Users/john.doe/Library/Caches/pypoetry/virtualenvs/nitpick-UU_pZ5zs-py3.7/lib/python3.7/site-packages/nitpick-0.24.1.dist-info/entry_points.txt
11:setup_cfg=nitpick.plugins.setup_cfg
Remove and recreate the virtualenv; this should fix it.
During development, you can run invoke clean --venv install --dry
.
It will display the commands that would be executed; remove --dry
to actually run them.
Executable .tox/lint/bin/pylint
not found
You might get this error while running make
locally.
Run
invoke lint
(ortox -e lint
directly) to create this tox environment.Run
make
again.
Contributing
Contributions are welcome, and they are greatly appreciated! Every little bit helps, and credit will always be given.
Check the projects on GitHub, you might help coding a planned feature.
Bug reports or feature requests
First, search the GitHub issue tracker to see if your bug/feature is already there.
If nothing is found, just add a new issue and follow the instructions.
Documentation improvements
Nitpick could always use more documentation, whether as part of the official docs, in docstrings, or even on the web in blog posts, articles, and such.
Development
To set up Nitpick for local development:
Fork Nitpick (look for the “Fork” button).
Clone your fork locally:
cd ~/Code git clone git@github.com:your_name_here/nitpick.git cd nitpick
Install Poetry globally using the recommended way.
Install Invoke. You can use pipx to install it globally:
pipx install invoke
.Install dependencies and pre-commit hooks:
invoke install --hooks
Create a branch for local development:
git checkout -b name-of-your-bugfix-or-feature
Now you can make your changes locally.
When you’re done making changes, run tests and checks locally with:
# Quick tests and checks make # Or use this to simulate a full CI build with tox invoke ci-build
Commit your changes and push your branch to GitHub:
git add . # For a feature: git commit -m "feat: short description of your feature" # For a bug fix: git commit -m "fix: short description of what you fixed" git push origin name-of-your-bugfix-or-feature
Submit a pull request through the GitHub website.
Commit convention
Nitpick follows Conventional Commits
No need to rebase the commits in your branch. If your pull request is accepted, all your commits will be squashed into a single one, and the commit message will be adjusted to follow the current standard.
Pull Request Guidelines
If you need some code review or feedback while you’re developing the code, just make a draft pull request.
For merging, follow the checklist on the pull request template itself.
When running invoke test
: if you don’t have all the necessary Python versions available locally (needed by tox), you can rely on GitHub Workflows.
Tests will run for each change you add in the pull request.
It will be slower though…
nitpick
nitpick package
Main module.
- class nitpick.Nitpick[source]
Bases:
object
The Nitpick API.
- configured_files(*partial_names: str) List[pathlib.Path] [source]
List of files configured in the Nitpick style. Filter only the selected partial names.
- echo(message: str)[source]
Echo a message on the terminal, with the relative path at the beginning.
- enforce_present_absent(*partial_names: str) Iterator[nitpick.violations.Fuss] [source]
Enforce files that should be present or absent.
- Parameters
partial_names – Names of the files to enforce configs for.
- Returns
Fuss generator.
- enforce_style(*partial_names: str, autofix=True) Iterator[nitpick.violations.Fuss] [source]
Read the merged style and enforce the rules in it.
Get all root keys from the merged style (every key is a filename, except “nitpick”).
For each file name, find the plugin(s) that can handle the file.
- Parameters
partial_names – Names of the files to enforce configs for.
autofix – Flag to modify files, if the plugin supports it (default: True).
- Returns
Fuss generator.
- init(project_root: Optional[Union[pathlib.Path, str]] = None, offline: Optional[bool] = None) nitpick.core.Nitpick [source]
Initialize attributes of the singleton.
- project: nitpick.project.Project
- run(*partial_names: str, autofix=False) Iterator[nitpick.violations.Fuss] [source]
Run Nitpick.
- Parameters
partial_names – Names of the files to enforce configs for.
autofix – Flag to modify files, if the plugin supports it (default: True).
- Returns
Fuss generator.
- classmethod singleton() nitpick.core.Nitpick [source]
Return a single instance of the class.
Subpackages
nitpick.plugins package
Hook specifications used by Nitpick plugins.
Note
The hook specifications and the plugin classes are still experimental and considered as an internal API. They might change at any time; use at your own risk.
Submodules
Base class for file checkers.
- class nitpick.plugins.base.NitpickPlugin(info: nitpick.plugins.info.FileInfo, expected_config: Dict[str, Any], autofix=False)[source]
Bases:
object
Base class for Nitpick plugins.
- Parameters
data – File information (project, path, tags).
expected_config – Expected configuration for the file
autofix – Flag to modify files, if the plugin supports it (default: True).
- abstract enforce_rules() Iterator[nitpick.violations.Fuss] [source]
Enforce rules for this file. It must be overridden by inherited classes if needed.
- entry_point() Iterator[nitpick.violations.Fuss] [source]
Entry point of the Nitpick plugin.
- filename = ''
- identify_tags: set[str] = {}
Which
identify
tags thisnitpick.plugins.base.NitpickPlugin
child recognises.
- property nitpick_file_dict: Dict[str, Any]
Nitpick configuration for this file as a TOML dict, taken from the style file.
- post_init()[source]
Hook for plugin initialization after the instance was created.
The name mimics
__post_init__()
on dataclasses, without the magic double underscores: Post-init processing
- predefined_special_config() nitpick.config.SpecialConfig [source]
Create a predefined special configuration for this plugin. Each plugin can override this method.
- skip_empty_suggestion = False
- validation_schema: Schema | None = None
Nested validation field for this file, to be applied in runtime when the validation schema is rebuilt. Useful when you have a strict configuration for a file type (e.g.
nitpick.plugins.json.JsonPlugin
).
Info needed by the plugins.
- class nitpick.plugins.info.FileInfo(project: nitpick.project.Project, path_from_root: str, tags: typing.Set[str] = <factory>)[source]
Bases:
object
File information needed by the plugin.
- classmethod create(project: nitpick.project.Project, path_from_root: str) nitpick.plugins.info.FileInfo [source]
Clean the file name and get its tags.
- project: nitpick.project.Project
INI files.
- class nitpick.plugins.ini.IniPlugin(info: nitpick.plugins.info.FileInfo, expected_config: Dict[str, Any], autofix=False)[source]
Bases:
nitpick.plugins.base.NitpickPlugin
Enforce configurations and autofix INI files.
Examples of
.ini
files handled by this plugin:Style examples enforcing values on INI files: flake8 configuration.
- add_options_before_space(section: str, options: dict) None [source]
Add new options before a blank line in the end of the section.
- compare_different_keys(section, key, raw_actual: Any, raw_expected: Any) Iterator[nitpick.violations.Fuss] [source]
Compare different keys, with special treatment when they are lists or numeric.
- static contents_without_top_section(multiline_text: str) str [source]
Remove the temporary top section from multiline text, and keep the newline at the end of the file.
- enforce_comma_separated_values(section, key, raw_actual: Any, raw_expected: Any) Iterator[nitpick.violations.Fuss] [source]
Enforce sections and keys with comma-separated values. The values might contain spaces.
- enforce_missing_sections() Iterator[nitpick.violations.Fuss] [source]
Enforce missing sections.
- enforce_rules() Iterator[nitpick.violations.Fuss] [source]
Enforce rules on missing sections and missing key/value pairs in an INI file.
- enforce_section(section: str) Iterator[nitpick.violations.Fuss] [source]
Enforce rules for a section.
- entry_point() Iterator[nitpick.violations.Fuss]
Entry point of the Nitpick plugin.
- expected_config: JsonDict
- file_path: Path
- filename = ''
- static get_example_cfg(parser: configparser.ConfigParser) str [source]
Print an example of a config parser in a string instead of a file.
- get_missing_output() str [source]
Get a missing output string example from the missing sections in an INI file.
- identify_tags: set[str] = {'editorconfig', 'ini'}
Which
identify
tags thisnitpick.plugins.base.NitpickPlugin
child recognises.
- property needs_top_section: bool
Return True if this .ini file needs a top section (e.g.: .editorconfig).
- property nitpick_file_dict: Dict[str, Any]
Nitpick configuration for this file as a TOML dict, taken from the style file.
- predefined_special_config() nitpick.config.SpecialConfig
Create a predefined special configuration for this plugin. Each plugin can override this method.
- show_missing_keys(section: str, values: list[tuple[str, Any]]) Iterator[Fuss] [source]
Show the keys that are not present in a section.
- skip_empty_suggestion = False
- updater: ConfigUpdater
- validation_schema: Schema | None = None
Nested validation field for this file, to be applied in runtime when the validation schema is rebuilt. Useful when you have a strict configuration for a file type (e.g.
nitpick.plugins.json.JsonPlugin
).
- class nitpick.plugins.ini.Violations(value)[source]
Bases:
nitpick.violations.ViolationEnum
Violations for this plugin.
- INVALID_COMMA_SEPARATED_VALUES_SECTION = (325, ': invalid sections on comma_separated_values:')
- MISSING_OPTION = (324, ': section [{section}] has some missing key/value pairs. Use this:')
- MISSING_SECTIONS = (321, ' has some missing sections. Use this:')
- MISSING_VALUES_IN_LIST = (322, ' has missing values in the {key!r} key. Include those values:')
- OPTION_HAS_DIFFERENT_VALUE = (323, ': [{section}]{key} is {actual} but it should be like this:')
- PARSING_ERROR = (326, ': parsing error ({cls}): {msg}')
- TOP_SECTION_HAS_DIFFERENT_VALUE = (327, ': {key} is {actual} but it should be:')
- TOP_SECTION_MISSING_OPTION = (328, ': top section has missing options. Use this:')
- nitpick.plugins.ini.can_handle(info: FileInfo) type[NitpickPlugin] | None [source]
Handle INI files.
- nitpick.plugins.ini.plugin_class() type[NitpickPlugin] [source]
Handle INI files.
JSON files.
- class nitpick.plugins.json.JsonFileSchema(*, only: types.StrSequenceOrSet | None = None, exclude: types.StrSequenceOrSet = (), many: bool = False, context: dict | None = None, load_only: types.StrSequenceOrSet = (), dump_only: types.StrSequenceOrSet = (), partial: bool | types.StrSequenceOrSet = False, unknown: str | None = None)[source]
Bases:
nitpick.schemas.BaseNitpickSchema
Validation schema for any JSON file added to the style.
- class Meta
Bases:
object
Options object for a Schema.
Example usage:
class Meta: fields = ("id", "email", "date_created") exclude = ("password", "secret_attribute")
Available options:
fields
: Tuple or list of fields to include in the serialized result.additional
: Tuple or list of fields to include in addition to theexplicitly declared fields.
additional
andfields
are mutually-exclusive options.
include
: Dictionary of additional fields to include in the schema. It isusually better to define fields as class variables, but you may need to use this option, e.g., if your fields are Python keywords. May be an OrderedDict.
exclude
: Tuple or list of fields to exclude in the serialized result.Nested fields can be represented with dot delimiters.
dateformat
: Default format for Date <fields.Date> fields.datetimeformat
: Default format for DateTime <fields.DateTime> fields.timeformat
: Default format for Time <fields.Time> fields.render_module
: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.Defaults to json from the standard library.
ordered
: If True, order serialization output according to theorder in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.
index_errors
: If True, errors dictionaries will include the indexof invalid items in a collection.
load_only
: Tuple or list of fields to exclude from serialized results.dump_only
: Tuple or list of fields to exclude from deserializationunknown
: Whether to exclude, include, or raise an error for unknownfields in the data. Use EXCLUDE, INCLUDE or RAISE.
register
: Whether to register the Schema with marshmallow’s internalclass registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.
- OPTIONS_CLASS
alias of
marshmallow.schema.SchemaOpts
- TYPE_MAPPING: Dict[type, Type[ma_fields.Field]] = {<class 'str'>: <class 'marshmallow.fields.String'>, <class 'bytes'>: <class 'marshmallow.fields.String'>, <class 'datetime.datetime'>: <class 'marshmallow.fields.DateTime'>, <class 'float'>: <class 'marshmallow.fields.Float'>, <class 'bool'>: <class 'marshmallow.fields.Boolean'>, <class 'tuple'>: <class 'marshmallow.fields.Raw'>, <class 'list'>: <class 'marshmallow.fields.Raw'>, <class 'set'>: <class 'marshmallow.fields.Raw'>, <class 'int'>: <class 'marshmallow.fields.Integer'>, <class 'uuid.UUID'>: <class 'marshmallow.fields.UUID'>, <class 'datetime.time'>: <class 'marshmallow.fields.Time'>, <class 'datetime.date'>: <class 'marshmallow.fields.Date'>, <class 'datetime.timedelta'>: <class 'marshmallow.fields.TimeDelta'>, <class 'decimal.Decimal'>: <class 'marshmallow.fields.Decimal'>}
- dump(obj: Any, *, many: bool | None = None)
Serialize an object to native Python data types according to this Schema’s fields.
- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
Serialized data
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.
- dumps(obj: Any, *args, many: bool | None = None, **kwargs)
Same as
dump()
, except return a JSON-encoded string.- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A
json
string
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.
- error_messages: Dict[str, str] = {'unknown': 'Unknown configuration. See https://nitpick.rtfd.io/en/latest/nitpick_section.html.'}
Overrides for default schema-level error messages
- classmethod from_dict(fields: dict[str, ma_fields.Field | type], *, name: str = 'GeneratedSchema') type
Generate a Schema class given a dictionary of fields.
from marshmallow import Schema, fields PersonSchema = Schema.from_dict({"name": fields.Str()}) print(PersonSchema().load({"name": "David"})) # => {'name': 'David'}
Generated schemas are not added to the class registry and therefore cannot be referred to by name in Nested fields.
- Parameters
New in version 3.0.0.
- get_attribute(obj: Any, attr: str, default: Any)
Defines how to pull values from an object to serialize.
New in version 2.0.0.
Changed in version 3.0.0a1: Changed position of
obj
andattr
.
- handle_error(error: marshmallow.exceptions.ValidationError, data: Any, *, many: bool, **kwargs)
Custom error handler function for the schema.
- Parameters
error – The ValidationError raised during (de)serialization.
data – The original input data.
many – Value of
many
on dump or load.partial – Value of
partial
on load.
New in version 2.0.0.
Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.
- load(data: Mapping[str, Any] | Iterable[Mapping[str, Any]], *, many: bool | None = None, partial: bool | types.StrSequenceOrSet | None = None, unknown: str | None = None)
Deserialize a data structure to an object defined by this Schema’s fields.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
- Returns
Deserialized data
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the deserialized data rather than a
(data, errors)
duple. AValidationError
is raised if invalid data are passed.
- loads(json_data: str, *, many: bool | None = None, partial: bool | types.StrSequenceOrSet | None = None, unknown: str | None = None, **kwargs)
Same as
load()
, except it takes a JSON string as input.- Parameters
json_data – A JSON string of the data to deserialize.
many – Whether to deserialize obj as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
- Returns
Deserialized data
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the deserialized data rather than a
(data, errors)
duple. AValidationError
is raised if invalid data are passed.
- on_bind_field(field_name: str, field_obj: marshmallow.fields.Field) None
Hook to modify a field when it is bound to the Schema.
No-op by default.
- opts: SchemaOpts = <marshmallow.schema.SchemaOpts object>
- validate(data: Mapping[str, Any] | Iterable[Mapping[str, Any]], *, many: bool | None = None, partial: bool | types.StrSequenceOrSet | None = None) dict[str, list[str]]
Validate data against the schema, returning a dictionary of validation errors.
- Parameters
data – The data to validate.
many – Whether to validate data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.
- Returns
A dictionary of validation errors.
New in version 1.1.0.
- class nitpick.plugins.json.JsonPlugin(info: nitpick.plugins.info.FileInfo, expected_config: Dict[str, Any], autofix=False)[source]
Bases:
nitpick.plugins.base.NitpickPlugin
Enforce configurations and autofix JSON files.
Add the configurations for the file name you wish to check. Style example: the default config for package.json.
- enforce_rules() Iterator[nitpick.violations.Fuss] [source]
Enforce rules for missing keys and JSON content.
- entry_point() Iterator[nitpick.violations.Fuss]
Entry point of the Nitpick plugin.
- expected_config: JsonDict
- file_path: Path
- filename = ''
- identify_tags: set[str] = {'json'}
Which
identify
tags thisnitpick.plugins.base.NitpickPlugin
child recognises.
- property nitpick_file_dict: Dict[str, Any]
Nitpick configuration for this file as a TOML dict, taken from the style file.
- post_init()
Hook for plugin initialization after the instance was created.
The name mimics
__post_init__()
on dataclasses, without the magic double underscores: Post-init processing
- predefined_special_config() nitpick.config.SpecialConfig
Create a predefined special configuration for this plugin. Each plugin can override this method.
- report(violation: ViolationEnum, blender: JsonDict, change: BaseDoc | None)[source]
Report a violation while optionally modifying the JSON dict.
- skip_empty_suggestion = False
- validation_schema
alias of
nitpick.plugins.json.JsonFileSchema
- nitpick.plugins.json.can_handle(info: FileInfo) type[NitpickPlugin] | None [source]
Handle JSON files.
- nitpick.plugins.json.plugin_class() type[NitpickPlugin] [source]
Handle JSON files.
Text files.
- class nitpick.plugins.text.TextItemSchema(*, only: types.StrSequenceOrSet | None = None, exclude: types.StrSequenceOrSet = (), many: bool = False, context: dict | None = None, load_only: types.StrSequenceOrSet = (), dump_only: types.StrSequenceOrSet = (), partial: bool | types.StrSequenceOrSet = False, unknown: str | None = None)[source]
Bases:
marshmallow.schema.Schema
Validation schema for the object inside
contains
.- class Meta
Bases:
object
Options object for a Schema.
Example usage:
class Meta: fields = ("id", "email", "date_created") exclude = ("password", "secret_attribute")
Available options:
fields
: Tuple or list of fields to include in the serialized result.additional
: Tuple or list of fields to include in addition to theexplicitly declared fields.
additional
andfields
are mutually-exclusive options.
include
: Dictionary of additional fields to include in the schema. It isusually better to define fields as class variables, but you may need to use this option, e.g., if your fields are Python keywords. May be an OrderedDict.
exclude
: Tuple or list of fields to exclude in the serialized result.Nested fields can be represented with dot delimiters.
dateformat
: Default format for Date <fields.Date> fields.datetimeformat
: Default format for DateTime <fields.DateTime> fields.timeformat
: Default format for Time <fields.Time> fields.render_module
: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.Defaults to json from the standard library.
ordered
: If True, order serialization output according to theorder in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.
index_errors
: If True, errors dictionaries will include the indexof invalid items in a collection.
load_only
: Tuple or list of fields to exclude from serialized results.dump_only
: Tuple or list of fields to exclude from deserializationunknown
: Whether to exclude, include, or raise an error for unknownfields in the data. Use EXCLUDE, INCLUDE or RAISE.
register
: Whether to register the Schema with marshmallow’s internalclass registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.
- OPTIONS_CLASS
alias of
marshmallow.schema.SchemaOpts
- TYPE_MAPPING: Dict[type, Type[ma_fields.Field]] = {<class 'str'>: <class 'marshmallow.fields.String'>, <class 'bytes'>: <class 'marshmallow.fields.String'>, <class 'datetime.datetime'>: <class 'marshmallow.fields.DateTime'>, <class 'float'>: <class 'marshmallow.fields.Float'>, <class 'bool'>: <class 'marshmallow.fields.Boolean'>, <class 'tuple'>: <class 'marshmallow.fields.Raw'>, <class 'list'>: <class 'marshmallow.fields.Raw'>, <class 'set'>: <class 'marshmallow.fields.Raw'>, <class 'int'>: <class 'marshmallow.fields.Integer'>, <class 'uuid.UUID'>: <class 'marshmallow.fields.UUID'>, <class 'datetime.time'>: <class 'marshmallow.fields.Time'>, <class 'datetime.date'>: <class 'marshmallow.fields.Date'>, <class 'datetime.timedelta'>: <class 'marshmallow.fields.TimeDelta'>, <class 'decimal.Decimal'>: <class 'marshmallow.fields.Decimal'>}
- dump(obj: Any, *, many: bool | None = None)
Serialize an object to native Python data types according to this Schema’s fields.
- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
Serialized data
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.
- dumps(obj: Any, *args, many: bool | None = None, **kwargs)
Same as
dump()
, except return a JSON-encoded string.- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A
json
string
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.
- error_messages: Dict[str, str] = {'unknown': 'Unknown configuration. See https://nitpick.rtfd.io/en/latest/plugins.html#text-files.'}
Overrides for default schema-level error messages
- classmethod from_dict(fields: dict[str, ma_fields.Field | type], *, name: str = 'GeneratedSchema') type
Generate a Schema class given a dictionary of fields.
from marshmallow import Schema, fields PersonSchema = Schema.from_dict({"name": fields.Str()}) print(PersonSchema().load({"name": "David"})) # => {'name': 'David'}
Generated schemas are not added to the class registry and therefore cannot be referred to by name in Nested fields.
- Parameters
New in version 3.0.0.
- get_attribute(obj: Any, attr: str, default: Any)
Defines how to pull values from an object to serialize.
New in version 2.0.0.
Changed in version 3.0.0a1: Changed position of
obj
andattr
.
- handle_error(error: marshmallow.exceptions.ValidationError, data: Any, *, many: bool, **kwargs)
Custom error handler function for the schema.
- Parameters
error – The ValidationError raised during (de)serialization.
data – The original input data.
many – Value of
many
on dump or load.partial – Value of
partial
on load.
New in version 2.0.0.
Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.
- load(data: Mapping[str, Any] | Iterable[Mapping[str, Any]], *, many: bool | None = None, partial: bool | types.StrSequenceOrSet | None = None, unknown: str | None = None)
Deserialize a data structure to an object defined by this Schema’s fields.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
- Returns
Deserialized data
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the deserialized data rather than a
(data, errors)
duple. AValidationError
is raised if invalid data are passed.
- loads(json_data: str, *, many: bool | None = None, partial: bool | types.StrSequenceOrSet | None = None, unknown: str | None = None, **kwargs)
Same as
load()
, except it takes a JSON string as input.- Parameters
json_data – A JSON string of the data to deserialize.
many – Whether to deserialize obj as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
- Returns
Deserialized data
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the deserialized data rather than a
(data, errors)
duple. AValidationError
is raised if invalid data are passed.
- on_bind_field(field_name: str, field_obj: marshmallow.fields.Field) None
Hook to modify a field when it is bound to the Schema.
No-op by default.
- opts: SchemaOpts = <marshmallow.schema.SchemaOpts object>
- validate(data: Mapping[str, Any] | Iterable[Mapping[str, Any]], *, many: bool | None = None, partial: bool | types.StrSequenceOrSet | None = None) dict[str, list[str]]
Validate data against the schema, returning a dictionary of validation errors.
- Parameters
data – The data to validate.
many – Whether to validate data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.
- Returns
A dictionary of validation errors.
New in version 1.1.0.
- class nitpick.plugins.text.TextPlugin(info: nitpick.plugins.info.FileInfo, expected_config: Dict[str, Any], autofix=False)[source]
Bases:
nitpick.plugins.base.NitpickPlugin
Enforce configuration on text files.
To check if
some.txt
file contains the linesabc
anddef
(in any order):[["some.txt".contains]] line = "abc" [["some.txt".contains]] line = "def"
- enforce_rules() Iterator[nitpick.violations.Fuss] [source]
Enforce rules for missing lines.
- entry_point() Iterator[nitpick.violations.Fuss]
Entry point of the Nitpick plugin.
- expected_config: JsonDict
- file_path: Path
- filename = ''
- identify_tags: set[str] = {'text'}
Which
identify
tags thisnitpick.plugins.base.NitpickPlugin
child recognises.
- property nitpick_file_dict: Dict[str, Any]
Nitpick configuration for this file as a TOML dict, taken from the style file.
- post_init()
Hook for plugin initialization after the instance was created.
The name mimics
__post_init__()
on dataclasses, without the magic double underscores: Post-init processing
- predefined_special_config() nitpick.config.SpecialConfig
Create a predefined special configuration for this plugin. Each plugin can override this method.
- skip_empty_suggestion = True
- validation_schema
alias of
nitpick.plugins.text.TextSchema
- class nitpick.plugins.text.TextSchema(*, only: types.StrSequenceOrSet | None = None, exclude: types.StrSequenceOrSet = (), many: bool = False, context: dict | None = None, load_only: types.StrSequenceOrSet = (), dump_only: types.StrSequenceOrSet = (), partial: bool | types.StrSequenceOrSet = False, unknown: str | None = None)[source]
Bases:
marshmallow.schema.Schema
Validation schema for the text file TOML configuration.
- class Meta
Bases:
object
Options object for a Schema.
Example usage:
class Meta: fields = ("id", "email", "date_created") exclude = ("password", "secret_attribute")
Available options:
fields
: Tuple or list of fields to include in the serialized result.additional
: Tuple or list of fields to include in addition to theexplicitly declared fields.
additional
andfields
are mutually-exclusive options.
include
: Dictionary of additional fields to include in the schema. It isusually better to define fields as class variables, but you may need to use this option, e.g., if your fields are Python keywords. May be an OrderedDict.
exclude
: Tuple or list of fields to exclude in the serialized result.Nested fields can be represented with dot delimiters.
dateformat
: Default format for Date <fields.Date> fields.datetimeformat
: Default format for DateTime <fields.DateTime> fields.timeformat
: Default format for Time <fields.Time> fields.render_module
: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.Defaults to json from the standard library.
ordered
: If True, order serialization output according to theorder in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.
index_errors
: If True, errors dictionaries will include the indexof invalid items in a collection.
load_only
: Tuple or list of fields to exclude from serialized results.dump_only
: Tuple or list of fields to exclude from deserializationunknown
: Whether to exclude, include, or raise an error for unknownfields in the data. Use EXCLUDE, INCLUDE or RAISE.
register
: Whether to register the Schema with marshmallow’s internalclass registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.
- OPTIONS_CLASS
alias of
marshmallow.schema.SchemaOpts
- TYPE_MAPPING: Dict[type, Type[ma_fields.Field]] = {<class 'str'>: <class 'marshmallow.fields.String'>, <class 'bytes'>: <class 'marshmallow.fields.String'>, <class 'datetime.datetime'>: <class 'marshmallow.fields.DateTime'>, <class 'float'>: <class 'marshmallow.fields.Float'>, <class 'bool'>: <class 'marshmallow.fields.Boolean'>, <class 'tuple'>: <class 'marshmallow.fields.Raw'>, <class 'list'>: <class 'marshmallow.fields.Raw'>, <class 'set'>: <class 'marshmallow.fields.Raw'>, <class 'int'>: <class 'marshmallow.fields.Integer'>, <class 'uuid.UUID'>: <class 'marshmallow.fields.UUID'>, <class 'datetime.time'>: <class 'marshmallow.fields.Time'>, <class 'datetime.date'>: <class 'marshmallow.fields.Date'>, <class 'datetime.timedelta'>: <class 'marshmallow.fields.TimeDelta'>, <class 'decimal.Decimal'>: <class 'marshmallow.fields.Decimal'>}
- dump(obj: Any, *, many: bool | None = None)
Serialize an object to native Python data types according to this Schema’s fields.
- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
Serialized data
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.
- dumps(obj: Any, *args, many: bool | None = None, **kwargs)
Same as
dump()
, except return a JSON-encoded string.- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A
json
string
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.
- error_messages: Dict[str, str] = {'unknown': 'Unknown configuration. See https://nitpick.rtfd.io/en/latest/plugins.html#text-files.'}
Overrides for default schema-level error messages
- classmethod from_dict(fields: dict[str, ma_fields.Field | type], *, name: str = 'GeneratedSchema') type
Generate a Schema class given a dictionary of fields.
from marshmallow import Schema, fields PersonSchema = Schema.from_dict({"name": fields.Str()}) print(PersonSchema().load({"name": "David"})) # => {'name': 'David'}
Generated schemas are not added to the class registry and therefore cannot be referred to by name in Nested fields.
- Parameters
New in version 3.0.0.
- get_attribute(obj: Any, attr: str, default: Any)
Defines how to pull values from an object to serialize.
New in version 2.0.0.
Changed in version 3.0.0a1: Changed position of
obj
andattr
.
- handle_error(error: marshmallow.exceptions.ValidationError, data: Any, *, many: bool, **kwargs)
Custom error handler function for the schema.
- Parameters
error – The ValidationError raised during (de)serialization.
data – The original input data.
many – Value of
many
on dump or load.partial – Value of
partial
on load.
New in version 2.0.0.
Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.
- load(data: Mapping[str, Any] | Iterable[Mapping[str, Any]], *, many: bool | None = None, partial: bool | types.StrSequenceOrSet | None = None, unknown: str | None = None)
Deserialize a data structure to an object defined by this Schema’s fields.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
- Returns
Deserialized data
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the deserialized data rather than a
(data, errors)
duple. AValidationError
is raised if invalid data are passed.
- loads(json_data: str, *, many: bool | None = None, partial: bool | types.StrSequenceOrSet | None = None, unknown: str | None = None, **kwargs)
Same as
load()
, except it takes a JSON string as input.- Parameters
json_data – A JSON string of the data to deserialize.
many – Whether to deserialize obj as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
- Returns
Deserialized data
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the deserialized data rather than a
(data, errors)
duple. AValidationError
is raised if invalid data are passed.
- on_bind_field(field_name: str, field_obj: marshmallow.fields.Field) None
Hook to modify a field when it is bound to the Schema.
No-op by default.
- opts: SchemaOpts = <marshmallow.schema.SchemaOpts object>
- validate(data: Mapping[str, Any] | Iterable[Mapping[str, Any]], *, many: bool | None = None, partial: bool | types.StrSequenceOrSet | None = None) dict[str, list[str]]
Validate data against the schema, returning a dictionary of validation errors.
- Parameters
data – The data to validate.
many – Whether to validate data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.
- Returns
A dictionary of validation errors.
New in version 1.1.0.
- class nitpick.plugins.text.Violations(value)[source]
Bases:
nitpick.violations.ViolationEnum
Violations for this plugin.
- MISSING_LINES = (352, ' has missing lines:')
- nitpick.plugins.text.can_handle(info: FileInfo) type[NitpickPlugin] | None [source]
Handle text files.
- nitpick.plugins.text.plugin_class() type[NitpickPlugin] [source]
Handle text files.
TOML files.
- class nitpick.plugins.toml.TomlPlugin(info: nitpick.plugins.info.FileInfo, expected_config: Dict[str, Any], autofix=False)[source]
Bases:
nitpick.plugins.base.NitpickPlugin
Enforce configurations and autofix TOML files.
E.g.: pyproject.toml (PEP 518).
See also the [tool.poetry] section of the pyproject.toml file.
Style example: Python 3.8 version constraint. There are many other examples here.
- enforce_rules() Iterator[nitpick.violations.Fuss] [source]
Enforce rules for missing key/value pairs in the TOML file.
- entry_point() Iterator[nitpick.violations.Fuss]
Entry point of the Nitpick plugin.
- expected_config: JsonDict
- file_path: Path
- filename = ''
- identify_tags: set[str] = {'toml'}
Which
identify
tags thisnitpick.plugins.base.NitpickPlugin
child recognises.
- property nitpick_file_dict: Dict[str, Any]
Nitpick configuration for this file as a TOML dict, taken from the style file.
- post_init()
Hook for plugin initialization after the instance was created.
The name mimics
__post_init__()
on dataclasses, without the magic double underscores: Post-init processing
- predefined_special_config() nitpick.config.SpecialConfig
Create a predefined special configuration for this plugin. Each plugin can override this method.
- report(violation: ViolationEnum, document: TOMLDocument | None, change: BaseDoc | None)[source]
Report a violation while optionally modifying the TOML document.
- skip_empty_suggestion = False
- validation_schema: Schema | None = None
Nested validation field for this file, to be applied in runtime when the validation schema is rebuilt. Useful when you have a strict configuration for a file type (e.g.
nitpick.plugins.json.JsonPlugin
).
- nitpick.plugins.toml.can_handle(info: FileInfo) type[NitpickPlugin] | None [source]
Handle TOML files.
- nitpick.plugins.toml.plugin_class() type[NitpickPlugin] [source]
Handle TOML files.
YAML files.
- class nitpick.plugins.yaml.YamlPlugin(info: nitpick.plugins.info.FileInfo, expected_config: Dict[str, Any], autofix=False)[source]
Bases:
nitpick.plugins.base.NitpickPlugin
Enforce configurations and autofix YAML files.
Example: .pre-commit-config.yaml.
Style example: the default pre-commit hooks.
Warning
The plugin tries to preserve comments in the YAML file by using the
ruamel.yaml
package. It works for most cases. If your comment was removed, place them in a different place of the fil and try again. If it still doesn’t work, please report a bug.Known issue: lists like
args
andadditional_dependencies
might be joined in a single line, and comments between items will be removed. Move your comments outside these lists, and they should be preserved.Note
No validation of
.pre-commit-config.yaml
will be done anymore in this generic YAML plugin. Nitpick will not validate hooks and missing keys as it did before; it’s not the purpose of this package.- enforce_rules() Iterator[nitpick.violations.Fuss] [source]
Enforce rules for missing data in the YAML file.
- entry_point() Iterator[nitpick.violations.Fuss]
Entry point of the Nitpick plugin.
- expected_config: JsonDict
- file_path: Path
- filename = ''
- identify_tags: set[str] = {'yaml'}
Which
identify
tags thisnitpick.plugins.base.NitpickPlugin
child recognises.
- property nitpick_file_dict: Dict[str, Any]
Nitpick configuration for this file as a TOML dict, taken from the style file.
- post_init()
Hook for plugin initialization after the instance was created.
The name mimics
__post_init__()
on dataclasses, without the magic double underscores: Post-init processing
- predefined_special_config() nitpick.config.SpecialConfig [source]
Predefined special config, with list keys for .pre-commit-config.yaml and GitHub Workflow files.
- report(violation: ViolationEnum, yaml_object: YamlObject, change: YamlDoc | None, replacement: YamlDoc | None = None)[source]
Report a violation while optionally modifying the YAML document.
- skip_empty_suggestion = False
- validation_schema: Schema | None = None
Nested validation field for this file, to be applied in runtime when the validation schema is rebuilt. Useful when you have a strict configuration for a file type (e.g.
nitpick.plugins.json.JsonPlugin
).
- nitpick.plugins.yaml.can_handle(info: FileInfo) type[NitpickPlugin] | None [source]
Handle YAML files.
- nitpick.plugins.yaml.plugin_class() type[NitpickPlugin] [source]
Handle YAML files.
nitpick.resources package
A library of Nitpick styles. Building blocks that can be combined and reused.
Subpackages
Styles for any language.
Styles for JavaScript.
Styles for Kotlin.
Style presets.
Styles for Protobuf files.
Styles for Python.
Styles for shell scripts.
nitpick.style package
Styles parsing and merging.
- class nitpick.style.StyleManager(project: nitpick.project.Project, offline: bool, cache_option: str)[source]
Bases:
object
Include styles recursively from one another.
- property cache_dir: pathlib.Path
Clear the cache directory (on the project root or on the current directory).
- static file_field_pair(filename: str, base_file_class: type[NitpickPlugin]) dict[str, fields.Field] [source]
Return a schema field with info from a config file class.
- find_initial_styles(configured_styles: Union[str, Iterable[str]]) Iterator[nitpick.violations.Fuss] [source]
Find the initial style(s) and include them.
- get_style_path(style_uri: str) tuple[Path | None, str] [source]
Get the style path from the URI. Add the .toml extension if it’s missing.
- include_multiple_styles(chosen_styles: Union[str, Iterable[str]]) Iterator[nitpick.violations.Fuss] [source]
Include a list of styles (or just one) into this style tree.
- load_fixed_name_plugins() Set[Type[nitpick.plugins.base.NitpickPlugin]] [source]
Separate classes with fixed file names from classes with dynamic files names.
- merge_toml_dict() Dict[str, Any] [source]
Merge all included styles into a TOML (actually JSON) dictionary.
- project: nitpick.project.Project
- nitpick.style.parse_cache_option(cache_option: str) Tuple[nitpick.enums.CachingEnum, datetime.timedelta] [source]
Parse the cache option provided on pyproject.toml.
If no cache if provided or is invalid, the default is one hour.
Subpackages
Style fetchers with protocol support.
- class nitpick.style.fetchers.Scheme(value)[source]
Bases:
strenum.LowercaseStrEnum
URL schemes.
- GH = 'gh'
- GITHUB = 'github'
- HTTP = 'http'
- HTTPS = 'https'
- PY = 'py'
- PYPACKAGE = 'pypackage'
- class nitpick.style.fetchers.StyleFetcherManager(offline: bool, cache_dir: str, cache_option: str)[source]
Bases:
object
Manager that controls which fetcher to be used given a protocol.
- cache_repository: Repository
- fetch(url) Tuple[Optional[pathlib.Path], str] [source]
Determine which fetcher to be used and fetch from it.
Try a fetcher by domain first, then by protocol scheme.
- fetchers: FetchersType
Base class for fetchers that wrap inner fetchers with caching ability.
- class nitpick.style.fetchers.base.StyleFetcher(cache_manager: CacheManager, cache_option: str, protocols: tuple = (), domains: tuple[str, ...] = ())[source]
Bases:
object
Base class of all fetchers, it encapsulate get/fetch from cache.
- cache_manager: CacheManager
- fetch(url) Tuple[Optional[pathlib.Path], str] [source]
Fetch a style form cache or from a specific fetcher.
- requires_connection = False
Basic local file fetcher.
- class nitpick.style.fetchers.file.FileFetcher(cache_manager: CacheManager, cache_option: str, protocols: tuple = ('file', ''), domains: tuple[str, ...] = ())[source]
Bases:
nitpick.style.fetchers.base.StyleFetcher
Fetch a style from a local file.
- cache_manager: CacheManager
- fetch(url) Tuple[Optional[pathlib.Path], str]
Fetch a style form cache or from a specific fetcher.
- requires_connection = False
Support for gh
and github
schemes.
- class nitpick.style.fetchers.github.GitHubFetcher(cache_manager: CacheManager, cache_option: str, protocols: tuple = (<Scheme.GH: 'gh'>, <Scheme.GITHUB: 'github'>), domains: tuple[str, ...] = ('github.com', ))[source]
Bases:
nitpick.style.fetchers.http.HttpFetcher
Fetch styles from GitHub repositories.
- cache_manager: CacheManager
- fetch(url) Tuple[Optional[pathlib.Path], str]
Fetch a style form cache or from a specific fetcher.
- requires_connection = True
- class nitpick.style.fetchers.github.GitHubURL(owner: str, repository: str, git_reference: str, path: str, auth_token: str | None = None, query_string: tuple | None = None)[source]
Bases:
object
Represent a GitHub URL, created from a URL or from its parts.
- property credentials: tuple
Credentials encoded in this URL.
A tuple of
(api_token, '')
if present, or empty tuple otherwise. If the value ofapi_token
begins with$
, it will be replaced with the value of the environment corresponding to the remaining part of the string.
- property default_branch: str
Default GitHub branch.
This property performs a HTTP request and it’s memoized with
lru_cache()
.
- property git_reference_or_default: str
Return the Git reference if informed, or return the default branch.
- classmethod parse_url(url: str) nitpick.style.fetchers.github.GitHubURL [source]
Create an instance by parsing a URL string in any accepted format.
See the code for
test_parsing_github_urls()
for more examples.
- nitpick.style.fetchers.github.get_default_branch(api_url: str) str [source]
Get the default branch from the GitHub repo using the API.
For now, the request is not authenticated on GitHub, so it might hit a rate limit with:
requests.exceptions.HTTPError: 403 Client Error: rate limit exceeded for url
This function is using
lru_cache()
as a simple memoizer, trying to avoid this rate limit error.Another option for the future: perform an authenticated request to GitHub. That would require a
requests.Session
and some user credentials.
Base HTTP fetcher, other fetchers can inherit from this to wrap http errors.
- class nitpick.style.fetchers.http.HttpFetcher(cache_manager: CacheManager, cache_option: str, protocols: tuple = (<Scheme.HTTP: 'http'>, <Scheme.HTTPS: 'https'>), domains: tuple[str, ...] = ())[source]
Bases:
nitpick.style.fetchers.base.StyleFetcher
Fetch a style from an http/https server.
- cache_manager: CacheManager
- fetch(url) Tuple[Optional[pathlib.Path], str]
Fetch a style form cache or from a specific fetcher.
- requires_connection = True
Support for py
schemes.
- class nitpick.style.fetchers.pypackage.BuiltinStyle(*, py_url: str, py_url_without_ext: str, path_from_repo_root: str, path_from_resources_root: str)[source]
Bases:
object
A built-in style file in TOML format.
Method generated by attrs for class BuiltinStyle.
- classmethod from_path(resource_path: pathlib.Path) nitpick.style.fetchers.pypackage.BuiltinStyle [source]
Create a built-in style from a resource path.
- pypackage_url: PythonPackageURL
- class nitpick.style.fetchers.pypackage.PythonPackageFetcher(cache_manager: CacheManager, cache_option: str, protocols: tuple = (<Scheme.PY: 'py'>, <Scheme.PYPACKAGE: 'pypackage'>), domains: tuple[str, ...] = ())[source]
Bases:
nitpick.style.fetchers.base.StyleFetcher
Fetch a style from an installed Python package.
URL schemes: -
py://import/path/of/style/file/<style_file_name>
-pypackage://import/path/of/style/file/<style_file_name>
E.g.
py://some_package/path/nitpick.toml
.- cache_manager: CacheManager
- fetch(url) Tuple[Optional[pathlib.Path], str]
Fetch a style form cache or from a specific fetcher.
- requires_connection = False
- class nitpick.style.fetchers.pypackage.PythonPackageURL(import_path: str, resource_name: str)[source]
Bases:
object
Represent a resource file in installed Python package.
- classmethod parse_url(url: str) nitpick.style.fetchers.pypackage.PythonPackageURL [source]
Create an instance by parsing a URL string in any accepted format.
See the code for
test_parsing_python_package_urls()
for more examples.
- property raw_content_url: importlib_resources.abc.Traversable
Raw path of resource file.
- nitpick.style.fetchers.pypackage.builtin_resources_root() pathlib.Path [source]
Built-in resources root.
- nitpick.style.fetchers.pypackage.builtin_styles() Iterable[pathlib.Path] [source]
List the built-in styles.
- nitpick.style.fetchers.pypackage.repo_root() pathlib.Path [source]
Repository root, 3 levels up from the resources root.
Submodules
Cache functions and configuration for styles.
- nitpick.style.cache.parse_cache_option(cache_option: str) Tuple[nitpick.enums.CachingEnum, datetime.timedelta] [source]
Parse the cache option provided on pyproject.toml.
If no cache if provided or is invalid, the default is one hour.
Config validator.
Style files.
- class nitpick.style.core.StyleManager(project: nitpick.project.Project, offline: bool, cache_option: str)[source]
Bases:
object
Include styles recursively from one another.
- property cache_dir: pathlib.Path
Clear the cache directory (on the project root or on the current directory).
- static file_field_pair(filename: str, base_file_class: type[NitpickPlugin]) dict[str, fields.Field] [source]
Return a schema field with info from a config file class.
- find_initial_styles(configured_styles: Union[str, Iterable[str]]) Iterator[nitpick.violations.Fuss] [source]
Find the initial style(s) and include them.
- get_style_path(style_uri: str) tuple[Path | None, str] [source]
Get the style path from the URI. Add the .toml extension if it’s missing.
- include_multiple_styles(chosen_styles: Union[str, Iterable[str]]) Iterator[nitpick.violations.Fuss] [source]
Include a list of styles (or just one) into this style tree.
- load_fixed_name_plugins() Set[Type[nitpick.plugins.base.NitpickPlugin]] [source]
Separate classes with fixed file names from classes with dynamic files names.
- merge_toml_dict() Dict[str, Any] [source]
Merge all included styles into a TOML (actually JSON) dictionary.
- project: nitpick.project.Project
Submodules
nitpick.blender module
Dictionary blender and configuration file formats.
- class nitpick.blender.BaseDoc(*, path: Optional[Union[pathlib.Path, str]] = None, string: Optional[str] = None, obj: Optional[Dict[str, Any]] = None)[source]
Bases:
object
Base class for configuration file formats.
- Parameters
path – Path of the config file to be loaded.
string – Config in string format.
obj – Config object (Python dict, YamlDoc, TomlDoc instances).
- property as_object: dict
String content converted to a Python object (dict, YAML object instance, etc.).
- class nitpick.blender.Comparison(actual: nitpick.blender.TBaseDoc, expected: Dict[str, Any], special_config: nitpick.config.SpecialConfig)[source]
Bases:
object
A comparison between two dictionaries, computing missing items and differences.
- class nitpick.blender.ElementDetail(data: ElementData, key: str | list[str], index: int, scalar: bool, compact: str)[source]
Bases:
object
Detailed information about an element of a list.
Method generated by attrs for class ElementDetail.
- data: ElementData
- class nitpick.blender.InlineTableTomlDecoder(_dict=<class 'dict'>)[source]
Bases:
toml.decoder.TomlDecoder
A hacky decoder to work around some bug (or unfinished work) in the Python TOML package.
https://github.com/uiri/toml/issues/362.
- bounded_string(s)
- embed_comments(idx, currentlevel)
- get_empty_inline_table()[source]
Hackity hack for a crappy unmaintained package.
Total lack of respect, the guy doesn’t even reply: https://github.com/uiri/toml/issues/361
- get_empty_table()
- load_array(a)
- load_inline_object(line, currentlevel, multikey=False, multibackslash=False)
- load_line(line, currentlevel, multikey, multibackslash)
- load_value(v, strictly_valid=True)
- preserve_comment(line_no, key, comment, beginline)
- class nitpick.blender.JsonDoc(*, path: Optional[Union[pathlib.Path, str]] = None, string: Optional[str] = None, obj: Optional[Dict[str, Any]] = None)[source]
Bases:
nitpick.blender.BaseDoc
JSON configuration format.
- property as_object: dict
String content converted to a Python object (dict, YAML object instance, etc.).
- class nitpick.blender.ListDetail(data: ListOrCommentedSeq, elements: list[ElementDetail])[source]
Bases:
object
Detailed info about a list.
Method generated by attrs for class ListDetail.
- data: ListOrCommentedSeq
- elements: list[ElementDetail]
- find_by_key(desired: ElementDetail) ElementDetail | None [source]
Find an element by key.
- nitpick.blender.SEPARATOR_QUOTED_SPLIT = '#$@'
Special unique separator for
nitpick.blender.quoted_split()
.
- class nitpick.blender.SensibleYAML[source]
Bases:
ruamel.yaml.main.YAML
YAML with sensible defaults but an inefficient dump to string.
- typ: ‘rt’/None -> RoundTripLoader/RoundTripDumper, (default)
‘safe’ -> SafeLoader/SafeDumper, ‘unsafe’ -> normal/unsafe Loader/Dumper ‘base’ -> baseloader
pure: if True only use Python modules input/output: needed to work as context manager plug_ins: a list of plug-in files
- Xdump_all(documents: Any, stream: Any, *, transform: Any = None) Any
Serialize a sequence of Python objects into a YAML stream.
- property block_seq_indent
- compose(stream: Union[Path, StreamTextType]) Any
Parse the first YAML document in a stream and produce the corresponding representation tree.
- compose_all(stream: Union[Path, StreamTextType]) Any
Parse all YAML documents in a stream and produce corresponding representation trees.
- property composer
- property constructor
- dump(data: Any, stream: Union[Path, StreamType] = None, *, transform: Any = None) Any
- dump_all(documents: Any, stream: Union[Path, StreamType], *, transform: Any = None) Any
- dumps(data) str [source]
Dump to a string… who would want such a thing? One can dump to a file or stdout.
- emit(events: Any, stream: Any) None
Emit YAML parsing events into a stream. If stream is None, return the produced string instead.
- property emitter
- get_constructor_parser(stream: StreamTextType) Any
the old cyaml needs special setup, and therefore the stream
- get_serializer_representer_emitter(stream: StreamType, tlca: Any) Any
- property indent
- load(stream: Union[Path, StreamTextType]) Any
at this point you either have the non-pure Parser (which has its own reader and scanner) or you have the pure Parser. If the pure Parser is set, then set the Reader and Scanner, if not already set. If either the Scanner or Reader are set, you cannot use the non-pure Parser,
so reset it to the pure parser and set the Reader resp. Scanner if necessary
- load_all(stream: Union[Path, StreamTextType]) Any
- loads(string: str)[source]
Load YAML from a string… that unusual use case in a world of files only.
- map(**kw: Any) Any
- official_plug_ins() Any
search for list of subdirs that are plug-ins, if __file__ is not available, e.g. single file installers that are not properly emulating a file-system (issue 324) no plug-ins will be found. If any are packaged, you know which file that are and you can explicitly provide it during instantiation:
yaml = ruamel.yaml.YAML(plug_ins=[‘ruamel/yaml/jinja2/__plug_in__’])
- parse(stream: StreamTextType) Any
Parse a YAML stream and produce parsing events.
- property parser
- property reader
- register_class(cls: Any) Any
register a class for dumping loading - if it has attribute yaml_tag use that to register, else use class name - if it has methods to_yaml/from_yaml use those to dump/load else dump attributes
as mapping
- property representer
- property resolver
- scan(stream: StreamTextType) Any
Scan a YAML stream and produce scanning tokens.
- property scanner
- seq(*args: Any) Any
- serialize(node: Any, stream: Optional[StreamType]) Any
Serialize a representation tree into a YAML stream. If stream is None, return the produced string instead.
- serialize_all(nodes: Any, stream: Optional[StreamType]) Any
Serialize a sequence of representation trees into a YAML stream. If stream is None, return the produced string instead.
- property serializer
- class nitpick.blender.TomlDoc(*, path: Optional[Union[pathlib.Path, str]] = None, string: Optional[str] = None, obj: Optional[Dict[str, Any]] = None, use_tomlkit=False)[source]
Bases:
nitpick.blender.BaseDoc
TOML configuration format.
- property as_object: dict
String content converted to a Python object (dict, YAML object instance, etc.).
- class nitpick.blender.YamlDoc(*, path: Optional[Union[pathlib.Path, str]] = None, string: Optional[str] = None, obj: Optional[Dict[str, Any]] = None)[source]
Bases:
nitpick.blender.BaseDoc
YAML configuration format.
- property as_object: dict
String content converted to a Python object (dict, YAML object instance, etc.).
- property as_string: str
Contents of the file or the original string provided when the instance was created.
- property reformatted: str
Reformat the configuration dict as a new string (it might not match the original string/file contents).
- updater: SensibleYAML
- nitpick.blender.compare_lists_with_dictdiffer(actual: list | dict, expected: list | dict, *, return_list: bool = True) list | dict [source]
Compare two lists using dictdiffer.
- nitpick.blender.custom_reducer(separator: str) Callable [source]
Custom reducer for
flatten_dict.flatten_dict.flatten()
accepting a separator.
- nitpick.blender.custom_splitter(separator: str) Callable [source]
Custom splitter for
flatten_dict.flatten_dict.unflatten()
accepting a separator.
- nitpick.blender.flatten_quotes(dict_: Dict[str, Any], separator='.') Dict[str, Any] [source]
Flatten a dict keeping quotes in keys.
- nitpick.blender.is_scalar(value: Union[Dict[str, Any], List[Any], str, float]) bool [source]
Return True if the value is NOT a dict or a list.
- nitpick.blender.quote_reducer(separator: str) Callable [source]
Reducer used to unflatten dicts. Quote keys when they have dots.
- nitpick.blender.quoted_split(string_: str, separator='.') list[str] [source]
Split a string by a separator, but considering quoted parts (single or double quotes).
>>> quoted_split("my.key.without.quotes") ['my', 'key', 'without', 'quotes'] >>> quoted_split('"double.quoted.string"') ['double.quoted.string'] >>> quoted_split('"double.quoted.string".and.after') ['double.quoted.string', 'and', 'after'] >>> quoted_split('something.before."double.quoted.string"') ['something', 'before', 'double.quoted.string'] >>> quoted_split("'single.quoted.string'") ['single.quoted.string'] >>> quoted_split("'single.quoted.string'.and.after") ['single.quoted.string', 'and', 'after'] >>> quoted_split("something.before.'single.quoted.string'") ['something', 'before', 'single.quoted.string']
- nitpick.blender.quotes_splitter(flat_key: str) tuple[str, ...] [source]
Split keys keeping quoted strings together.
- nitpick.blender.replace_or_add_list_element(yaml_obj: Union[ruamel.yaml.comments.CommentedSeq, ruamel.yaml.comments.CommentedMap], element: Any, key: str, index: int) None [source]
Replace or add a new element in a YAML sequence of mappings.
- nitpick.blender.search_json(json_data: ElementData, jmespath_expression: ParsedResult | str, default: Any = None) Any [source]
Search a dictionary or list using a JMESPath expression. Return a default value if not found.
>>> data = {"root": {"app": [1, 2], "test": "something"}} >>> search_json(data, "root.app", None) [1, 2] >>> search_json(data, "root.test", None) 'something' >>> search_json(data, "root.unknown", "") '' >>> search_json(data, "root.unknown", None)
>>> search_json(data, "root.unknown")
>>> search_json(data, jmespath.compile("root.app"), []) [1, 2] >>> search_json(data, jmespath.compile("root.whatever"), "xxx") 'xxx' >>> search_json(data, "")
>>> search_json(data, None)
- Parameters
jmespath_expression – A compiled JMESPath expression or a string with an expression.
json_data – The dictionary to be searched.
default – Default value in case nothing is found.
- Returns
The object that was found or the default value.
- nitpick.blender.set_key_if_not_empty(dict_: Dict[str, Any], key: str, value: Any) None [source]
Update the dict if the value is valid.
nitpick.cli module
Module that contains the command line app.
Why does this file exist, and why not put this in __main__?
You might be tempted to import things from __main__ later, but that will cause problems: the code will get executed twice:
- When you run python -mnitpick python will execute
__main__.py
as a script. That means there won’t be any
nitpick.__main__
insys.modules
.
- When you run python -mnitpick python will execute
- When you import __main__ it will get executed again (as a module) because
there’s no
nitpick.__main__
insys.modules
.
Also see (1) from https://click.palletsprojects.com/en/5.x/setuptools/#setuptools-integration
- nitpick.cli.common_fix_or_check(context, verbose: int, files, check_only: bool) None [source]
Common CLI code for both “fix” and “check” commands.
- nitpick.cli.get_nitpick(context: click.core.Context) nitpick.core.Nitpick [source]
Create a Nitpick instance from the click context parameters.
nitpick.compat module
Handle import compatibility issues.
nitpick.config module
Special configurations.
- class nitpick.config.OverridableConfig(from_plugin: Dict[str, Any] = NOTHING, from_style: Dict[str, Any] = NOTHING, value: Dict[str, Any] = NOTHING)[source]
Bases:
object
Configs formed from defaults from the plugin that can be overridden by the style.
Method generated by attrs for class OverridableConfig.
- class nitpick.config.SpecialConfig(list_keys: nitpick.config.OverridableConfig = NOTHING)[source]
Bases:
object
Special configurations for plugins.
Method generated by attrs for class SpecialConfig.
- list_keys: nitpick.config.OverridableConfig
nitpick.constants module
Constants.
nitpick.core module
The Nitpick application.
- class nitpick.core.Nitpick[source]
Bases:
object
The Nitpick API.
- configured_files(*partial_names: str) List[pathlib.Path] [source]
List of files configured in the Nitpick style. Filter only the selected partial names.
- echo(message: str)[source]
Echo a message on the terminal, with the relative path at the beginning.
- enforce_present_absent(*partial_names: str) Iterator[nitpick.violations.Fuss] [source]
Enforce files that should be present or absent.
- Parameters
partial_names – Names of the files to enforce configs for.
- Returns
Fuss generator.
- enforce_style(*partial_names: str, autofix=True) Iterator[nitpick.violations.Fuss] [source]
Read the merged style and enforce the rules in it.
Get all root keys from the merged style (every key is a filename, except “nitpick”).
For each file name, find the plugin(s) that can handle the file.
- Parameters
partial_names – Names of the files to enforce configs for.
autofix – Flag to modify files, if the plugin supports it (default: True).
- Returns
Fuss generator.
- init(project_root: Optional[Union[pathlib.Path, str]] = None, offline: Optional[bool] = None) nitpick.core.Nitpick [source]
Initialize attributes of the singleton.
- project: nitpick.project.Project
- run(*partial_names: str, autofix=False) Iterator[nitpick.violations.Fuss] [source]
Run Nitpick.
- Parameters
partial_names – Names of the files to enforce configs for.
autofix – Flag to modify files, if the plugin supports it (default: True).
- Returns
Fuss generator.
- classmethod singleton() nitpick.core.Nitpick [source]
Return a single instance of the class.
nitpick.enums module
Enums.
- class nitpick.enums.CachingEnum(value)[source]
Bases:
enum.IntEnum
Caching modes for styles.
- EXPIRES = 3
The cache expires after the configured amount of time (minutes/hours/days).
- FOREVER = 2
Once the style(s) are cached, they never expire.
- NEVER = 1
Never cache, the style file(s) are always looked-up.
nitpick.exceptions module
Nitpick exceptions.
- class nitpick.exceptions.Deprecation[source]
Bases:
object
All deprecation messages in a single class.
When it’s time to break compatibility, remove a method/warning below, and older config files will trigger validation errors on Nitpick.
- static jsonfile_section(style_errors: Dict[str, Any]) bool [source]
The [nitpick.JSONFile] is not needed anymore; JSON files are now detected by the extension.
- exception nitpick.exceptions.QuitComplainingError(violations: Union[nitpick.violations.Fuss, List[nitpick.violations.Fuss]])[source]
Bases:
Exception
Quit complaining and exit the application.
- args
- with_traceback()
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
nitpick.fields module
Custom Marshmallow fields and validators.
- class nitpick.fields.Dict(keys: Field | type | None = None, values: Field | type | None = None, **kwargs)[source]
Bases:
marshmallow.fields.Mapping
A dict field. Supports dicts and dict-like objects. Extends Mapping with dict as the mapping_type.
Example:
numbers = fields.Dict(keys=fields.Str(), values=fields.Float())
- Parameters
kwargs – The same keyword arguments that
Mapping
receives.
New in version 2.1.0.
- property context
The context dictionary for the parent
Schema
.
- property default
- default_error_messages = {'invalid': 'Not a valid mapping type.'}
Default error messages.
- deserialize(value: Any, attr: str | None = None, data: Mapping[str, Any] | None = None, **kwargs)
Deserialize
value
.- Parameters
value – The value to deserialize.
attr – The attribute/key in data to deserialize.
data – The raw input data passed to Schema.load.
kwargs – Field-specific keyword arguments.
- Raises
ValidationError – If an invalid value is passed or if a required value is missing.
- fail(key: str, **kwargs)
Helper method that raises a ValidationError with an error message from
self.error_messages
.Deprecated since version 3.0.0: Use make_error <marshmallow.fields.Field.make_error> instead.
- get_value(obj, attr, accessor=None, default=<marshmallow.missing>)
Return the value for a given key from an object.
- make_error(key: str, **kwargs) marshmallow.exceptions.ValidationError
Helper method to make a ValidationError with an error message from
self.error_messages
.
- property missing
- name = None
- parent = None
- root = None
- serialize(attr: str, obj: Any, accessor: Callable[[Any, str, Any], Any] | None = None, **kwargs)
Pulls the value for the given key from the object, applies the field’s formatting and returns the result.
- Parameters
attr – The attribute/key to get from the object.
obj – The object to access the attribute/key from.
accessor – Function used to access values from
obj
.kwargs – Field-specific keyword arguments.
- class nitpick.fields.Field(*, load_default: typing.Any = <marshmallow.missing>, missing: typing.Any = <marshmallow.missing>, dump_default: typing.Any = <marshmallow.missing>, default: typing.Any = <marshmallow.missing>, data_key: str | None = None, attribute: str | None = None, validate: None | (typing.Callable[[typing.Any], typing.Any] | typing.Iterable[typing.Callable[[typing.Any], typing.Any]]) = None, required: bool = False, allow_none: bool | None = None, load_only: bool = False, dump_only: bool = False, error_messages: dict[str, str] | None = None, metadata: typing.Mapping[str, typing.Any] | None = None, **additional_metadata)[source]
Bases:
marshmallow.base.FieldABC
Basic field from which other fields should extend. It applies no formatting by default, and should only be used in cases where data does not need to be formatted before being serialized or deserialized. On error, the name of the field will be returned.
- Parameters
dump_default – If set, this value will be used during serialization if the input value is missing. If not set, the field will be excluded from the serialized output if the input value is missing. May be a value or a callable.
load_default – Default deserialization value for the field if the field is not found in the input data. May be a value or a callable.
data_key – The name of the dict key in the external representation, i.e. the input of load and the output of dump. If None, the key will match the name of the field.
attribute – The name of the attribute to get the value from when serializing. If None, assumes the attribute has the same name as the field. Note: This should only be used for very specific use cases such as outputting multiple fields for a single attribute. In most cases, you should use
data_key
instead.validate – Validator or collection of validators that are called during deserialization. Validator takes a field’s input value as its only parameter and returns a boolean. If it returns False, an
ValidationError
is raised.required – Raise a
ValidationError
if the field value is not supplied during deserialization.allow_none – Set this to True if None should be considered a valid value during validation/deserialization. If
load_default=None
andallow_none
is unset, will default toTrue
. Otherwise, the default isFalse
.load_only – If True skip this field during serialization, otherwise its value will be present in the serialized data.
dump_only – If True skip this field during deserialization, otherwise its value will be present in the deserialized object. In the context of an HTTP API, this effectively marks the field as “read-only”.
error_messages (dict) – Overrides for Field.default_error_messages.
metadata – Extra information to be stored as field metadata.
Changed in version 2.0.0: Removed error parameter. Use
error_messages
instead.Changed in version 2.0.0: Added allow_none parameter, which makes validation/deserialization of None consistent across fields.
Changed in version 2.0.0: Added load_only and dump_only parameters, which allow field skipping during the (de)serialization process.
Changed in version 2.0.0: Added missing parameter, which indicates the value for a field if the field is not found during deserialization.
Changed in version 2.0.0:
default
value is only used if explicitly set. Otherwise, missing values inputs are excluded from serialized output.Changed in version 3.0.0b8: Add
data_key
parameter for the specifying the key in the input and output data. This parameter replaced bothload_from
anddump_to
.- property context
The context dictionary for the parent
Schema
.
- property default
- default_error_messages = {'null': 'Field may not be null.', 'required': 'Missing data for required field.', 'validator_failed': 'Invalid value.'}
Default error messages for various kinds of errors. The keys in this dictionary are passed to Field.make_error. The values are error messages passed to
marshmallow.exceptions.ValidationError
.
- deserialize(value: Any, attr: str | None = None, data: Mapping[str, Any] | None = None, **kwargs)[source]
Deserialize
value
.- Parameters
value – The value to deserialize.
attr – The attribute/key in data to deserialize.
data – The raw input data passed to Schema.load.
kwargs – Field-specific keyword arguments.
- Raises
ValidationError – If an invalid value is passed or if a required value is missing.
- fail(key: str, **kwargs)[source]
Helper method that raises a ValidationError with an error message from
self.error_messages
.Deprecated since version 3.0.0: Use make_error <marshmallow.fields.Field.make_error> instead.
- get_value(obj, attr, accessor=None, default=<marshmallow.missing>)[source]
Return the value for a given key from an object.
- make_error(key: str, **kwargs) marshmallow.exceptions.ValidationError [source]
Helper method to make a ValidationError with an error message from
self.error_messages
.
- property missing
- name = None
- parent = None
- root = None
- serialize(attr: str, obj: Any, accessor: Callable[[Any, str, Any], Any] | None = None, **kwargs)[source]
Pulls the value for the given key from the object, applies the field’s formatting and returns the result.
- Parameters
attr – The attribute/key to get from the object.
obj – The object to access the attribute/key from.
accessor – Function used to access values from
obj
.kwargs – Field-specific keyword arguments.
- class nitpick.fields.List(cls_or_instance: Field | type, **kwargs)[source]
Bases:
marshmallow.fields.Field
A list field, composed with another Field class or instance.
Example:
numbers = fields.List(fields.Float())
- Parameters
cls_or_instance – A field class or instance.
kwargs – The same keyword arguments that
Field
receives.
Changed in version 2.0.0: The
allow_none
parameter now applies to deserialization and has the same semantics as the other fields.Changed in version 3.0.0rc9: Does not serialize scalar values to single-item lists.
- property context
The context dictionary for the parent
Schema
.
- property default
- default_error_messages = {'invalid': 'Not a valid list.'}
Default error messages.
- deserialize(value: Any, attr: str | None = None, data: Mapping[str, Any] | None = None, **kwargs)
Deserialize
value
.- Parameters
value – The value to deserialize.
attr – The attribute/key in data to deserialize.
data – The raw input data passed to Schema.load.
kwargs – Field-specific keyword arguments.
- Raises
ValidationError – If an invalid value is passed or if a required value is missing.
- fail(key: str, **kwargs)
Helper method that raises a ValidationError with an error message from
self.error_messages
.Deprecated since version 3.0.0: Use make_error <marshmallow.fields.Field.make_error> instead.
- get_value(obj, attr, accessor=None, default=<marshmallow.missing>)
Return the value for a given key from an object.
- make_error(key: str, **kwargs) marshmallow.exceptions.ValidationError
Helper method to make a ValidationError with an error message from
self.error_messages
.
- property missing
- name = None
- parent = None
- root = None
- serialize(attr: str, obj: Any, accessor: Callable[[Any, str, Any], Any] | None = None, **kwargs)
Pulls the value for the given key from the object, applies the field’s formatting and returns the result.
- Parameters
attr – The attribute/key to get from the object.
obj – The object to access the attribute/key from.
accessor – Function used to access values from
obj
.kwargs – Field-specific keyword arguments.
- class nitpick.fields.Nested(nested: SchemaABC | type | str | dict[str, Field | type] | typing.Callable[[], SchemaABC | dict[str, Field | type]], *, dump_default: typing.Any = <marshmallow.missing>, default: typing.Any = <marshmallow.missing>, only: types.StrSequenceOrSet | None = None, exclude: types.StrSequenceOrSet = (), many: bool = False, unknown: str | None = None, **kwargs)[source]
Bases:
marshmallow.fields.Field
Allows you to nest a
Schema
inside a field.Examples:
class ChildSchema(Schema): id = fields.Str() name = fields.Str() # Use lambda functions when you need two-way nesting or self-nesting parent = fields.Nested(lambda: ParentSchema(only=("id",)), dump_only=True) siblings = fields.List(fields.Nested(lambda: ChildSchema(only=("id", "name")))) class ParentSchema(Schema): id = fields.Str() children = fields.List( fields.Nested(ChildSchema(only=("id", "parent", "siblings"))) ) spouse = fields.Nested(lambda: ParentSchema(only=("id",)))
When passing a Schema <marshmallow.Schema> instance as the first argument, the instance’s
exclude
,only
, andmany
attributes will be respected.Therefore, when passing the
exclude
,only
, ormany
arguments to fields.Nested, you should pass a Schema <marshmallow.Schema> class (not an instance) as the first argument.# Yes author = fields.Nested(UserSchema, only=('id', 'name')) # No author = fields.Nested(UserSchema(), only=('id', 'name'))
- Parameters
nested – Schema instance, class, class name (string), dictionary, or callable that returns a Schema or dictionary. Dictionaries are converted with Schema.from_dict.
exclude – A list or tuple of fields to exclude.
only – A list or tuple of fields to marshal. If None, all fields are marshalled. This parameter takes precedence over
exclude
.many – Whether the field is a collection of objects.
unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE.
kwargs – The same keyword arguments that
Field
receives.
- property context
The context dictionary for the parent
Schema
.
- property default
- default_error_messages = {'type': 'Invalid type.'}
Default error messages.
- deserialize(value: Any, attr: str | None = None, data: Mapping[str, Any] | None = None, **kwargs)
Deserialize
value
.- Parameters
value – The value to deserialize.
attr – The attribute/key in data to deserialize.
data – The raw input data passed to Schema.load.
kwargs – Field-specific keyword arguments.
- Raises
ValidationError – If an invalid value is passed or if a required value is missing.
- fail(key: str, **kwargs)
Helper method that raises a ValidationError with an error message from
self.error_messages
.Deprecated since version 3.0.0: Use make_error <marshmallow.fields.Field.make_error> instead.
- get_value(obj, attr, accessor=None, default=<marshmallow.missing>)
Return the value for a given key from an object.
- make_error(key: str, **kwargs) marshmallow.exceptions.ValidationError
Helper method to make a ValidationError with an error message from
self.error_messages
.
- property missing
- name = None
- parent = None
- root = None
- property schema
The nested Schema object.
Changed in version 1.0.0: Renamed from serializer to schema.
- serialize(attr: str, obj: Any, accessor: Callable[[Any, str, Any], Any] | None = None, **kwargs)
Pulls the value for the given key from the object, applies the field’s formatting and returns the result.
- Parameters
attr – The attribute/key to get from the object.
obj – The object to access the attribute/key from.
accessor – Function used to access values from
obj
.kwargs – Field-specific keyword arguments.
- class nitpick.fields.String(*, load_default: typing.Any = <marshmallow.missing>, missing: typing.Any = <marshmallow.missing>, dump_default: typing.Any = <marshmallow.missing>, default: typing.Any = <marshmallow.missing>, data_key: str | None = None, attribute: str | None = None, validate: None | (typing.Callable[[typing.Any], typing.Any] | typing.Iterable[typing.Callable[[typing.Any], typing.Any]]) = None, required: bool = False, allow_none: bool | None = None, load_only: bool = False, dump_only: bool = False, error_messages: dict[str, str] | None = None, metadata: typing.Mapping[str, typing.Any] | None = None, **additional_metadata)[source]
Bases:
marshmallow.fields.Field
A string field.
- Parameters
kwargs – The same keyword arguments that
Field
receives.
- property context
The context dictionary for the parent
Schema
.
- property default
- default_error_messages = {'invalid': 'Not a valid string.', 'invalid_utf8': 'Not a valid utf-8 string.'}
Default error messages.
- deserialize(value: Any, attr: str | None = None, data: Mapping[str, Any] | None = None, **kwargs)
Deserialize
value
.- Parameters
value – The value to deserialize.
attr – The attribute/key in data to deserialize.
data – The raw input data passed to Schema.load.
kwargs – Field-specific keyword arguments.
- Raises
ValidationError – If an invalid value is passed or if a required value is missing.
- fail(key: str, **kwargs)
Helper method that raises a ValidationError with an error message from
self.error_messages
.Deprecated since version 3.0.0: Use make_error <marshmallow.fields.Field.make_error> instead.
- get_value(obj, attr, accessor=None, default=<marshmallow.missing>)
Return the value for a given key from an object.
- make_error(key: str, **kwargs) marshmallow.exceptions.ValidationError
Helper method to make a ValidationError with an error message from
self.error_messages
.
- property missing
- name = None
- parent = None
- root = None
- serialize(attr: str, obj: Any, accessor: Callable[[Any, str, Any], Any] | None = None, **kwargs)
Pulls the value for the given key from the object, applies the field’s formatting and returns the result.
- Parameters
attr – The attribute/key to get from the object.
obj – The object to access the attribute/key from.
accessor – Function used to access values from
obj
.kwargs – Field-specific keyword arguments.
- nitpick.fields.URL
alias of
marshmallow.fields.Url
nitpick.flake8 module
Flake8 plugin to check files.
- class nitpick.flake8.NitpickFlake8Extension(tree=None, filename='(none)')[source]
Bases:
object
Main class for the flake8 extension.
Method generated by attrs for class NitpickFlake8Extension.
- static add_options(option_manager: flake8.options.manager.OptionManager)[source]
Add the offline option.
- build_flake8_error(obj: nitpick.violations.Fuss) Tuple[int, int, str, Type] [source]
Return a flake8 error from a fuss.
- collect_errors() Iterator[nitpick.violations.Fuss] [source]
Collect all possible Nitpick errors.
- name = 'nitpick'
- static parse_options(option_manager: flake8.options.manager.OptionManager, options, args)[source]
Create the Nitpick app, set logging from the verbose flags, set offline mode.
This function is called only once by flake8, so it’s a good place to create the app.
- version = '0.31.0'
nitpick.generic module
Generic functions and classes.
- nitpick.generic.filter_names(iterable: Iterable, *partial_names: str) list[str] [source]
Filter names and keep only the desired partial names.
Exclude the project name automatically.
>>> file_list = ['requirements.txt', 'tox.ini', 'setup.py', 'nitpick'] >>> filter_names(file_list) ['requirements.txt', 'tox.ini', 'setup.py'] >>> filter_names(file_list, 'ini', '.py') ['tox.ini', 'setup.py']
>>> mapping = {'requirements.txt': None, 'tox.ini': 1, 'setup.py': 2, 'nitpick': 3} >>> filter_names(mapping) ['requirements.txt', 'tox.ini', 'setup.py'] >>> filter_names(file_list, 'x') ['requirements.txt', 'tox.ini']
- nitpick.generic.is_url(url: str) bool [source]
Return True if a string is a URL.
>>> is_url("") False >>> is_url(" ") False >>> is_url("http://example.com") True >>> is_url("github://andreoliwa/nitpick/styles/black") True >>> is_url("github://$VARNAME@andreoliwa/nitpick/styles/black") True >>> is_url("github://LitErAl@andreoliwa/nitpick/styles/black") True >>> is_url("github://notfirst$@andreoliwa/nitpick/styles/black") True
- nitpick.generic.relative_to_current_dir(path_or_str: PathOrStr | None) str [source]
Return a relative path to the current dir or an absolute path.
- nitpick.generic.version_to_tuple(version: str = None) tuple[int, ...] [source]
Transform a version number into a tuple of integers, for comparison.
>>> version_to_tuple("") () >>> version_to_tuple(" ") () >>> version_to_tuple(None) () >>> version_to_tuple("1.0.1") (1, 0, 1) >>> version_to_tuple(" 0.2 ") (0, 2) >>> version_to_tuple(" 2 ") (2,)
- Parameters
version – String with the version number. It must be integers split by dots.
- Returns
Tuple with the version number.
nitpick.project module
A project to be nitpicked.
- class nitpick.project.Configuration(file: Path | None, styles: str | list[str], cache: str)[source]
Bases:
object
Configuration read from one of the
CONFIG_FILES
.
- class nitpick.project.Project(root: Optional[Union[pathlib.Path, str]] = None)[source]
Bases:
object
A project to be nitpicked.
- create_configuration(config: nitpick.project.Configuration) None [source]
Create a configuration file.
- merge_styles(offline: bool) Iterator[nitpick.violations.Fuss] [source]
Merge one or multiple style files.
- property plugin_manager: pluggy._manager.PluginManager
Load all defined plugins.
- read_configuration() nitpick.project.Configuration [source]
Search for a configuration file and validate it against a Marshmallow schema.
- property root: pathlib.Path
Root dir of the project.
- class nitpick.project.ToolNitpickSectionSchema(*, only: types.StrSequenceOrSet | None = None, exclude: types.StrSequenceOrSet = (), many: bool = False, context: dict | None = None, load_only: types.StrSequenceOrSet = (), dump_only: types.StrSequenceOrSet = (), partial: bool | types.StrSequenceOrSet = False, unknown: str | None = None)[source]
Bases:
nitpick.schemas.BaseNitpickSchema
Validation schema for the
[tool.nitpick]
section onpyproject.toml
.- class Meta
Bases:
object
Options object for a Schema.
Example usage:
class Meta: fields = ("id", "email", "date_created") exclude = ("password", "secret_attribute")
Available options:
fields
: Tuple or list of fields to include in the serialized result.additional
: Tuple or list of fields to include in addition to theexplicitly declared fields.
additional
andfields
are mutually-exclusive options.
include
: Dictionary of additional fields to include in the schema. It isusually better to define fields as class variables, but you may need to use this option, e.g., if your fields are Python keywords. May be an OrderedDict.
exclude
: Tuple or list of fields to exclude in the serialized result.Nested fields can be represented with dot delimiters.
dateformat
: Default format for Date <fields.Date> fields.datetimeformat
: Default format for DateTime <fields.DateTime> fields.timeformat
: Default format for Time <fields.Time> fields.render_module
: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.Defaults to json from the standard library.
ordered
: If True, order serialization output according to theorder in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.
index_errors
: If True, errors dictionaries will include the indexof invalid items in a collection.
load_only
: Tuple or list of fields to exclude from serialized results.dump_only
: Tuple or list of fields to exclude from deserializationunknown
: Whether to exclude, include, or raise an error for unknownfields in the data. Use EXCLUDE, INCLUDE or RAISE.
register
: Whether to register the Schema with marshmallow’s internalclass registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.
- OPTIONS_CLASS
alias of
marshmallow.schema.SchemaOpts
- TYPE_MAPPING: Dict[type, Type[ma_fields.Field]] = {<class 'str'>: <class 'marshmallow.fields.String'>, <class 'bytes'>: <class 'marshmallow.fields.String'>, <class 'datetime.datetime'>: <class 'marshmallow.fields.DateTime'>, <class 'float'>: <class 'marshmallow.fields.Float'>, <class 'bool'>: <class 'marshmallow.fields.Boolean'>, <class 'tuple'>: <class 'marshmallow.fields.Raw'>, <class 'list'>: <class 'marshmallow.fields.Raw'>, <class 'set'>: <class 'marshmallow.fields.Raw'>, <class 'int'>: <class 'marshmallow.fields.Integer'>, <class 'uuid.UUID'>: <class 'marshmallow.fields.UUID'>, <class 'datetime.time'>: <class 'marshmallow.fields.Time'>, <class 'datetime.date'>: <class 'marshmallow.fields.Date'>, <class 'datetime.timedelta'>: <class 'marshmallow.fields.TimeDelta'>, <class 'decimal.Decimal'>: <class 'marshmallow.fields.Decimal'>}
- dump(obj: Any, *, many: bool | None = None)
Serialize an object to native Python data types according to this Schema’s fields.
- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
Serialized data
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.
- dumps(obj: Any, *args, many: bool | None = None, **kwargs)
Same as
dump()
, except return a JSON-encoded string.- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A
json
string
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.
- error_messages: Dict[str, str] = {'unknown': 'Unknown configuration. See https://nitpick.rtfd.io/en/latest/configuration.html.'}
Overrides for default schema-level error messages
- classmethod from_dict(fields: dict[str, ma_fields.Field | type], *, name: str = 'GeneratedSchema') type
Generate a Schema class given a dictionary of fields.
from marshmallow import Schema, fields PersonSchema = Schema.from_dict({"name": fields.Str()}) print(PersonSchema().load({"name": "David"})) # => {'name': 'David'}
Generated schemas are not added to the class registry and therefore cannot be referred to by name in Nested fields.
- Parameters
New in version 3.0.0.
- get_attribute(obj: Any, attr: str, default: Any)
Defines how to pull values from an object to serialize.
New in version 2.0.0.
Changed in version 3.0.0a1: Changed position of
obj
andattr
.
- handle_error(error: marshmallow.exceptions.ValidationError, data: Any, *, many: bool, **kwargs)
Custom error handler function for the schema.
- Parameters
error – The ValidationError raised during (de)serialization.
data – The original input data.
many – Value of
many
on dump or load.partial – Value of
partial
on load.
New in version 2.0.0.
Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.
- load(data: Mapping[str, Any] | Iterable[Mapping[str, Any]], *, many: bool | None = None, partial: bool | types.StrSequenceOrSet | None = None, unknown: str | None = None)
Deserialize a data structure to an object defined by this Schema’s fields.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
- Returns
Deserialized data
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the deserialized data rather than a
(data, errors)
duple. AValidationError
is raised if invalid data are passed.
- loads(json_data: str, *, many: bool | None = None, partial: bool | types.StrSequenceOrSet | None = None, unknown: str | None = None, **kwargs)
Same as
load()
, except it takes a JSON string as input.- Parameters
json_data – A JSON string of the data to deserialize.
many – Whether to deserialize obj as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
- Returns
Deserialized data
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the deserialized data rather than a
(data, errors)
duple. AValidationError
is raised if invalid data are passed.
- on_bind_field(field_name: str, field_obj: marshmallow.fields.Field) None
Hook to modify a field when it is bound to the Schema.
No-op by default.
- opts: SchemaOpts = <marshmallow.schema.SchemaOpts object>
- validate(data: Mapping[str, Any] | Iterable[Mapping[str, Any]], *, many: bool | None = None, partial: bool | types.StrSequenceOrSet | None = None) dict[str, list[str]]
Validate data against the schema, returning a dictionary of validation errors.
- Parameters
data – The data to validate.
many – Whether to validate data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.
- Returns
A dictionary of validation errors.
New in version 1.1.0.
- nitpick.project.confirm_project_root(dir_: PathOrStr | None = None) Path [source]
Confirm this is the root dir of the project (the one that has one of the
ROOT_FILES
).
- nitpick.project.find_main_python_file(root_dir: pathlib.Path) pathlib.Path [source]
Find the main Python file in the root dir, the one that will be used to report Flake8 warnings.
The search order is: 1. Python files that belong to the root dir of the project (e.g.:
setup.py
,autoapp.py
). 2.manage.py
: they can be on the root or on a subdir (Django projects). 3. Any other*.py
Python file on the root dir and subdir. This avoid long recursions when there is anode_modules
subdir for instance.
nitpick.schemas module
Marshmallow schemas.
- class nitpick.schemas.BaseNitpickSchema(*, only: types.StrSequenceOrSet | None = None, exclude: types.StrSequenceOrSet = (), many: bool = False, context: dict | None = None, load_only: types.StrSequenceOrSet = (), dump_only: types.StrSequenceOrSet = (), partial: bool | types.StrSequenceOrSet = False, unknown: str | None = None)[source]
Bases:
marshmallow.schema.Schema
Base schema for all others, with default error messages.
- class Meta
Bases:
object
Options object for a Schema.
Example usage:
class Meta: fields = ("id", "email", "date_created") exclude = ("password", "secret_attribute")
Available options:
fields
: Tuple or list of fields to include in the serialized result.additional
: Tuple or list of fields to include in addition to theexplicitly declared fields.
additional
andfields
are mutually-exclusive options.
include
: Dictionary of additional fields to include in the schema. It isusually better to define fields as class variables, but you may need to use this option, e.g., if your fields are Python keywords. May be an OrderedDict.
exclude
: Tuple or list of fields to exclude in the serialized result.Nested fields can be represented with dot delimiters.
dateformat
: Default format for Date <fields.Date> fields.datetimeformat
: Default format for DateTime <fields.DateTime> fields.timeformat
: Default format for Time <fields.Time> fields.render_module
: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.Defaults to json from the standard library.
ordered
: If True, order serialization output according to theorder in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.
index_errors
: If True, errors dictionaries will include the indexof invalid items in a collection.
load_only
: Tuple or list of fields to exclude from serialized results.dump_only
: Tuple or list of fields to exclude from deserializationunknown
: Whether to exclude, include, or raise an error for unknownfields in the data. Use EXCLUDE, INCLUDE or RAISE.
register
: Whether to register the Schema with marshmallow’s internalclass registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.
- OPTIONS_CLASS
alias of
marshmallow.schema.SchemaOpts
- TYPE_MAPPING: Dict[type, Type[ma_fields.Field]] = {<class 'str'>: <class 'marshmallow.fields.String'>, <class 'bytes'>: <class 'marshmallow.fields.String'>, <class 'datetime.datetime'>: <class 'marshmallow.fields.DateTime'>, <class 'float'>: <class 'marshmallow.fields.Float'>, <class 'bool'>: <class 'marshmallow.fields.Boolean'>, <class 'tuple'>: <class 'marshmallow.fields.Raw'>, <class 'list'>: <class 'marshmallow.fields.Raw'>, <class 'set'>: <class 'marshmallow.fields.Raw'>, <class 'int'>: <class 'marshmallow.fields.Integer'>, <class 'uuid.UUID'>: <class 'marshmallow.fields.UUID'>, <class 'datetime.time'>: <class 'marshmallow.fields.Time'>, <class 'datetime.date'>: <class 'marshmallow.fields.Date'>, <class 'datetime.timedelta'>: <class 'marshmallow.fields.TimeDelta'>, <class 'decimal.Decimal'>: <class 'marshmallow.fields.Decimal'>}
- dump(obj: Any, *, many: bool | None = None)
Serialize an object to native Python data types according to this Schema’s fields.
- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
Serialized data
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.
- dumps(obj: Any, *args, many: bool | None = None, **kwargs)
Same as
dump()
, except return a JSON-encoded string.- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A
json
string
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.
- error_messages: Dict[str, str] = {'unknown': 'Unknown configuration. See https://nitpick.rtfd.io/en/latest/nitpick_section.html.'}
Overrides for default schema-level error messages
- classmethod from_dict(fields: dict[str, ma_fields.Field | type], *, name: str = 'GeneratedSchema') type
Generate a Schema class given a dictionary of fields.
from marshmallow import Schema, fields PersonSchema = Schema.from_dict({"name": fields.Str()}) print(PersonSchema().load({"name": "David"})) # => {'name': 'David'}
Generated schemas are not added to the class registry and therefore cannot be referred to by name in Nested fields.
- Parameters
New in version 3.0.0.
- get_attribute(obj: Any, attr: str, default: Any)
Defines how to pull values from an object to serialize.
New in version 2.0.0.
Changed in version 3.0.0a1: Changed position of
obj
andattr
.
- handle_error(error: marshmallow.exceptions.ValidationError, data: Any, *, many: bool, **kwargs)
Custom error handler function for the schema.
- Parameters
error – The ValidationError raised during (de)serialization.
data – The original input data.
many – Value of
many
on dump or load.partial – Value of
partial
on load.
New in version 2.0.0.
Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.
- load(data: Mapping[str, Any] | Iterable[Mapping[str, Any]], *, many: bool | None = None, partial: bool | types.StrSequenceOrSet | None = None, unknown: str | None = None)
Deserialize a data structure to an object defined by this Schema’s fields.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
- Returns
Deserialized data
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the deserialized data rather than a
(data, errors)
duple. AValidationError
is raised if invalid data are passed.
- loads(json_data: str, *, many: bool | None = None, partial: bool | types.StrSequenceOrSet | None = None, unknown: str | None = None, **kwargs)
Same as
load()
, except it takes a JSON string as input.- Parameters
json_data – A JSON string of the data to deserialize.
many – Whether to deserialize obj as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
- Returns
Deserialized data
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the deserialized data rather than a
(data, errors)
duple. AValidationError
is raised if invalid data are passed.
- on_bind_field(field_name: str, field_obj: marshmallow.fields.Field) None
Hook to modify a field when it is bound to the Schema.
No-op by default.
- opts: SchemaOpts = <marshmallow.schema.SchemaOpts object>
- validate(data: Mapping[str, Any] | Iterable[Mapping[str, Any]], *, many: bool | None = None, partial: bool | types.StrSequenceOrSet | None = None) dict[str, list[str]]
Validate data against the schema, returning a dictionary of validation errors.
- Parameters
data – The data to validate.
many – Whether to validate data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.
- Returns
A dictionary of validation errors.
New in version 1.1.0.
- class nitpick.schemas.BaseStyleSchema(*, only: types.StrSequenceOrSet | None = None, exclude: types.StrSequenceOrSet = (), many: bool = False, context: dict | None = None, load_only: types.StrSequenceOrSet = (), dump_only: types.StrSequenceOrSet = (), partial: bool | types.StrSequenceOrSet = False, unknown: str | None = None)[source]
Bases:
marshmallow.schema.Schema
Base validation schema for style files. Dynamic fields will be added to it later.
- class Meta
Bases:
object
Options object for a Schema.
Example usage:
class Meta: fields = ("id", "email", "date_created") exclude = ("password", "secret_attribute")
Available options:
fields
: Tuple or list of fields to include in the serialized result.additional
: Tuple or list of fields to include in addition to theexplicitly declared fields.
additional
andfields
are mutually-exclusive options.
include
: Dictionary of additional fields to include in the schema. It isusually better to define fields as class variables, but you may need to use this option, e.g., if your fields are Python keywords. May be an OrderedDict.
exclude
: Tuple or list of fields to exclude in the serialized result.Nested fields can be represented with dot delimiters.
dateformat
: Default format for Date <fields.Date> fields.datetimeformat
: Default format for DateTime <fields.DateTime> fields.timeformat
: Default format for Time <fields.Time> fields.render_module
: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.Defaults to json from the standard library.
ordered
: If True, order serialization output according to theorder in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.
index_errors
: If True, errors dictionaries will include the indexof invalid items in a collection.
load_only
: Tuple or list of fields to exclude from serialized results.dump_only
: Tuple or list of fields to exclude from deserializationunknown
: Whether to exclude, include, or raise an error for unknownfields in the data. Use EXCLUDE, INCLUDE or RAISE.
register
: Whether to register the Schema with marshmallow’s internalclass registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.
- OPTIONS_CLASS
alias of
marshmallow.schema.SchemaOpts
- TYPE_MAPPING: Dict[type, Type[ma_fields.Field]] = {<class 'str'>: <class 'marshmallow.fields.String'>, <class 'bytes'>: <class 'marshmallow.fields.String'>, <class 'datetime.datetime'>: <class 'marshmallow.fields.DateTime'>, <class 'float'>: <class 'marshmallow.fields.Float'>, <class 'bool'>: <class 'marshmallow.fields.Boolean'>, <class 'tuple'>: <class 'marshmallow.fields.Raw'>, <class 'list'>: <class 'marshmallow.fields.Raw'>, <class 'set'>: <class 'marshmallow.fields.Raw'>, <class 'int'>: <class 'marshmallow.fields.Integer'>, <class 'uuid.UUID'>: <class 'marshmallow.fields.UUID'>, <class 'datetime.time'>: <class 'marshmallow.fields.Time'>, <class 'datetime.date'>: <class 'marshmallow.fields.Date'>, <class 'datetime.timedelta'>: <class 'marshmallow.fields.TimeDelta'>, <class 'decimal.Decimal'>: <class 'marshmallow.fields.Decimal'>}
- dump(obj: Any, *, many: bool | None = None)
Serialize an object to native Python data types according to this Schema’s fields.
- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
Serialized data
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.
- dumps(obj: Any, *args, many: bool | None = None, **kwargs)
Same as
dump()
, except return a JSON-encoded string.- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A
json
string
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.
- error_messages: Dict[str, str] = {'unknown': 'Unknown file. See https://nitpick.rtfd.io/en/latest/plugins.html.'}
Overrides for default schema-level error messages
- classmethod from_dict(fields: dict[str, ma_fields.Field | type], *, name: str = 'GeneratedSchema') type
Generate a Schema class given a dictionary of fields.
from marshmallow import Schema, fields PersonSchema = Schema.from_dict({"name": fields.Str()}) print(PersonSchema().load({"name": "David"})) # => {'name': 'David'}
Generated schemas are not added to the class registry and therefore cannot be referred to by name in Nested fields.
- Parameters
New in version 3.0.0.
- get_attribute(obj: Any, attr: str, default: Any)
Defines how to pull values from an object to serialize.
New in version 2.0.0.
Changed in version 3.0.0a1: Changed position of
obj
andattr
.
- handle_error(error: marshmallow.exceptions.ValidationError, data: Any, *, many: bool, **kwargs)
Custom error handler function for the schema.
- Parameters
error – The ValidationError raised during (de)serialization.
data – The original input data.
many – Value of
many
on dump or load.partial – Value of
partial
on load.
New in version 2.0.0.
Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.
- load(data: Mapping[str, Any] | Iterable[Mapping[str, Any]], *, many: bool | None = None, partial: bool | types.StrSequenceOrSet | None = None, unknown: str | None = None)
Deserialize a data structure to an object defined by this Schema’s fields.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
- Returns
Deserialized data
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the deserialized data rather than a
(data, errors)
duple. AValidationError
is raised if invalid data are passed.
- loads(json_data: str, *, many: bool | None = None, partial: bool | types.StrSequenceOrSet | None = None, unknown: str | None = None, **kwargs)
Same as
load()
, except it takes a JSON string as input.- Parameters
json_data – A JSON string of the data to deserialize.
many – Whether to deserialize obj as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
- Returns
Deserialized data
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the deserialized data rather than a
(data, errors)
duple. AValidationError
is raised if invalid data are passed.
- on_bind_field(field_name: str, field_obj: marshmallow.fields.Field) None
Hook to modify a field when it is bound to the Schema.
No-op by default.
- opts: SchemaOpts = <marshmallow.schema.SchemaOpts object>
- validate(data: Mapping[str, Any] | Iterable[Mapping[str, Any]], *, many: bool | None = None, partial: bool | types.StrSequenceOrSet | None = None) dict[str, list[str]]
Validate data against the schema, returning a dictionary of validation errors.
- Parameters
data – The data to validate.
many – Whether to validate data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.
- Returns
A dictionary of validation errors.
New in version 1.1.0.
- class nitpick.schemas.IniSchema(*, only: types.StrSequenceOrSet | None = None, exclude: types.StrSequenceOrSet = (), many: bool = False, context: dict | None = None, load_only: types.StrSequenceOrSet = (), dump_only: types.StrSequenceOrSet = (), partial: bool | types.StrSequenceOrSet = False, unknown: str | None = None)[source]
Bases:
nitpick.schemas.BaseNitpickSchema
Validation schema for INI files.
- class Meta
Bases:
object
Options object for a Schema.
Example usage:
class Meta: fields = ("id", "email", "date_created") exclude = ("password", "secret_attribute")
Available options:
fields
: Tuple or list of fields to include in the serialized result.additional
: Tuple or list of fields to include in addition to theexplicitly declared fields.
additional
andfields
are mutually-exclusive options.
include
: Dictionary of additional fields to include in the schema. It isusually better to define fields as class variables, but you may need to use this option, e.g., if your fields are Python keywords. May be an OrderedDict.
exclude
: Tuple or list of fields to exclude in the serialized result.Nested fields can be represented with dot delimiters.
dateformat
: Default format for Date <fields.Date> fields.datetimeformat
: Default format for DateTime <fields.DateTime> fields.timeformat
: Default format for Time <fields.Time> fields.render_module
: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.Defaults to json from the standard library.
ordered
: If True, order serialization output according to theorder in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.
index_errors
: If True, errors dictionaries will include the indexof invalid items in a collection.
load_only
: Tuple or list of fields to exclude from serialized results.dump_only
: Tuple or list of fields to exclude from deserializationunknown
: Whether to exclude, include, or raise an error for unknownfields in the data. Use EXCLUDE, INCLUDE or RAISE.
register
: Whether to register the Schema with marshmallow’s internalclass registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.
- OPTIONS_CLASS
alias of
marshmallow.schema.SchemaOpts
- TYPE_MAPPING: Dict[type, Type[ma_fields.Field]] = {<class 'str'>: <class 'marshmallow.fields.String'>, <class 'bytes'>: <class 'marshmallow.fields.String'>, <class 'datetime.datetime'>: <class 'marshmallow.fields.DateTime'>, <class 'float'>: <class 'marshmallow.fields.Float'>, <class 'bool'>: <class 'marshmallow.fields.Boolean'>, <class 'tuple'>: <class 'marshmallow.fields.Raw'>, <class 'list'>: <class 'marshmallow.fields.Raw'>, <class 'set'>: <class 'marshmallow.fields.Raw'>, <class 'int'>: <class 'marshmallow.fields.Integer'>, <class 'uuid.UUID'>: <class 'marshmallow.fields.UUID'>, <class 'datetime.time'>: <class 'marshmallow.fields.Time'>, <class 'datetime.date'>: <class 'marshmallow.fields.Date'>, <class 'datetime.timedelta'>: <class 'marshmallow.fields.TimeDelta'>, <class 'decimal.Decimal'>: <class 'marshmallow.fields.Decimal'>}
- dump(obj: Any, *, many: bool | None = None)
Serialize an object to native Python data types according to this Schema’s fields.
- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
Serialized data
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.
- dumps(obj: Any, *args, many: bool | None = None, **kwargs)
Same as
dump()
, except return a JSON-encoded string.- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A
json
string
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.
- error_messages: Dict[str, str] = {'unknown': 'Unknown configuration. See https://nitpick.rtfd.io/en/latest/nitpick_section.html#comma-separated-values.'}
Overrides for default schema-level error messages
- classmethod from_dict(fields: dict[str, ma_fields.Field | type], *, name: str = 'GeneratedSchema') type
Generate a Schema class given a dictionary of fields.
from marshmallow import Schema, fields PersonSchema = Schema.from_dict({"name": fields.Str()}) print(PersonSchema().load({"name": "David"})) # => {'name': 'David'}
Generated schemas are not added to the class registry and therefore cannot be referred to by name in Nested fields.
- Parameters
New in version 3.0.0.
- get_attribute(obj: Any, attr: str, default: Any)
Defines how to pull values from an object to serialize.
New in version 2.0.0.
Changed in version 3.0.0a1: Changed position of
obj
andattr
.
- handle_error(error: marshmallow.exceptions.ValidationError, data: Any, *, many: bool, **kwargs)
Custom error handler function for the schema.
- Parameters
error – The ValidationError raised during (de)serialization.
data – The original input data.
many – Value of
many
on dump or load.partial – Value of
partial
on load.
New in version 2.0.0.
Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.
- load(data: Mapping[str, Any] | Iterable[Mapping[str, Any]], *, many: bool | None = None, partial: bool | types.StrSequenceOrSet | None = None, unknown: str | None = None)
Deserialize a data structure to an object defined by this Schema’s fields.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
- Returns
Deserialized data
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the deserialized data rather than a
(data, errors)
duple. AValidationError
is raised if invalid data are passed.
- loads(json_data: str, *, many: bool | None = None, partial: bool | types.StrSequenceOrSet | None = None, unknown: str | None = None, **kwargs)
Same as
load()
, except it takes a JSON string as input.- Parameters
json_data – A JSON string of the data to deserialize.
many – Whether to deserialize obj as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
- Returns
Deserialized data
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the deserialized data rather than a
(data, errors)
duple. AValidationError
is raised if invalid data are passed.
- on_bind_field(field_name: str, field_obj: marshmallow.fields.Field) None
Hook to modify a field when it is bound to the Schema.
No-op by default.
- opts: SchemaOpts = <marshmallow.schema.SchemaOpts object>
- validate(data: Mapping[str, Any] | Iterable[Mapping[str, Any]], *, many: bool | None = None, partial: bool | types.StrSequenceOrSet | None = None) dict[str, list[str]]
Validate data against the schema, returning a dictionary of validation errors.
- Parameters
data – The data to validate.
many – Whether to validate data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.
- Returns
A dictionary of validation errors.
New in version 1.1.0.
- class nitpick.schemas.NitpickFilesSectionSchema(*, only: types.StrSequenceOrSet | None = None, exclude: types.StrSequenceOrSet = (), many: bool = False, context: dict | None = None, load_only: types.StrSequenceOrSet = (), dump_only: types.StrSequenceOrSet = (), partial: bool | types.StrSequenceOrSet = False, unknown: str | None = None)[source]
Bases:
nitpick.schemas.BaseNitpickSchema
Validation schema for the
[nitpick.files]
section on the style file.- class Meta
Bases:
object
Options object for a Schema.
Example usage:
class Meta: fields = ("id", "email", "date_created") exclude = ("password", "secret_attribute")
Available options:
fields
: Tuple or list of fields to include in the serialized result.additional
: Tuple or list of fields to include in addition to theexplicitly declared fields.
additional
andfields
are mutually-exclusive options.
include
: Dictionary of additional fields to include in the schema. It isusually better to define fields as class variables, but you may need to use this option, e.g., if your fields are Python keywords. May be an OrderedDict.
exclude
: Tuple or list of fields to exclude in the serialized result.Nested fields can be represented with dot delimiters.
dateformat
: Default format for Date <fields.Date> fields.datetimeformat
: Default format for DateTime <fields.DateTime> fields.timeformat
: Default format for Time <fields.Time> fields.render_module
: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.Defaults to json from the standard library.
ordered
: If True, order serialization output according to theorder in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.
index_errors
: If True, errors dictionaries will include the indexof invalid items in a collection.
load_only
: Tuple or list of fields to exclude from serialized results.dump_only
: Tuple or list of fields to exclude from deserializationunknown
: Whether to exclude, include, or raise an error for unknownfields in the data. Use EXCLUDE, INCLUDE or RAISE.
register
: Whether to register the Schema with marshmallow’s internalclass registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.
- OPTIONS_CLASS
alias of
marshmallow.schema.SchemaOpts
- TYPE_MAPPING: Dict[type, Type[ma_fields.Field]] = {<class 'str'>: <class 'marshmallow.fields.String'>, <class 'bytes'>: <class 'marshmallow.fields.String'>, <class 'datetime.datetime'>: <class 'marshmallow.fields.DateTime'>, <class 'float'>: <class 'marshmallow.fields.Float'>, <class 'bool'>: <class 'marshmallow.fields.Boolean'>, <class 'tuple'>: <class 'marshmallow.fields.Raw'>, <class 'list'>: <class 'marshmallow.fields.Raw'>, <class 'set'>: <class 'marshmallow.fields.Raw'>, <class 'int'>: <class 'marshmallow.fields.Integer'>, <class 'uuid.UUID'>: <class 'marshmallow.fields.UUID'>, <class 'datetime.time'>: <class 'marshmallow.fields.Time'>, <class 'datetime.date'>: <class 'marshmallow.fields.Date'>, <class 'datetime.timedelta'>: <class 'marshmallow.fields.TimeDelta'>, <class 'decimal.Decimal'>: <class 'marshmallow.fields.Decimal'>}
- dump(obj: Any, *, many: bool | None = None)
Serialize an object to native Python data types according to this Schema’s fields.
- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
Serialized data
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.
- dumps(obj: Any, *args, many: bool | None = None, **kwargs)
Same as
dump()
, except return a JSON-encoded string.- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A
json
string
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.
- error_messages: Dict[str, str] = {'unknown': 'Unknown file. See https://nitpick.rtfd.io/en/latest/nitpick_section.html#nitpick-files.'}
Overrides for default schema-level error messages
- classmethod from_dict(fields: dict[str, ma_fields.Field | type], *, name: str = 'GeneratedSchema') type
Generate a Schema class given a dictionary of fields.
from marshmallow import Schema, fields PersonSchema = Schema.from_dict({"name": fields.Str()}) print(PersonSchema().load({"name": "David"})) # => {'name': 'David'}
Generated schemas are not added to the class registry and therefore cannot be referred to by name in Nested fields.
- Parameters
New in version 3.0.0.
- get_attribute(obj: Any, attr: str, default: Any)
Defines how to pull values from an object to serialize.
New in version 2.0.0.
Changed in version 3.0.0a1: Changed position of
obj
andattr
.
- handle_error(error: marshmallow.exceptions.ValidationError, data: Any, *, many: bool, **kwargs)
Custom error handler function for the schema.
- Parameters
error – The ValidationError raised during (de)serialization.
data – The original input data.
many – Value of
many
on dump or load.partial – Value of
partial
on load.
New in version 2.0.0.
Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.
- load(data: Mapping[str, Any] | Iterable[Mapping[str, Any]], *, many: bool | None = None, partial: bool | types.StrSequenceOrSet | None = None, unknown: str | None = None)
Deserialize a data structure to an object defined by this Schema’s fields.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
- Returns
Deserialized data
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the deserialized data rather than a
(data, errors)
duple. AValidationError
is raised if invalid data are passed.
- loads(json_data: str, *, many: bool | None = None, partial: bool | types.StrSequenceOrSet | None = None, unknown: str | None = None, **kwargs)
Same as
load()
, except it takes a JSON string as input.- Parameters
json_data – A JSON string of the data to deserialize.
many – Whether to deserialize obj as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
- Returns
Deserialized data
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the deserialized data rather than a
(data, errors)
duple. AValidationError
is raised if invalid data are passed.
- on_bind_field(field_name: str, field_obj: marshmallow.fields.Field) None
Hook to modify a field when it is bound to the Schema.
No-op by default.
- opts: SchemaOpts = <marshmallow.schema.SchemaOpts object>
- validate(data: Mapping[str, Any] | Iterable[Mapping[str, Any]], *, many: bool | None = None, partial: bool | types.StrSequenceOrSet | None = None) dict[str, list[str]]
Validate data against the schema, returning a dictionary of validation errors.
- Parameters
data – The data to validate.
many – Whether to validate data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.
- Returns
A dictionary of validation errors.
New in version 1.1.0.
- class nitpick.schemas.NitpickMetaSchema(*, only: types.StrSequenceOrSet | None = None, exclude: types.StrSequenceOrSet = (), many: bool = False, context: dict | None = None, load_only: types.StrSequenceOrSet = (), dump_only: types.StrSequenceOrSet = (), partial: bool | types.StrSequenceOrSet = False, unknown: str | None = None)[source]
Bases:
nitpick.schemas.BaseNitpickSchema
Meta info about a specific TOML style file.
- class Meta
Bases:
object
Options object for a Schema.
Example usage:
class Meta: fields = ("id", "email", "date_created") exclude = ("password", "secret_attribute")
Available options:
fields
: Tuple or list of fields to include in the serialized result.additional
: Tuple or list of fields to include in addition to theexplicitly declared fields.
additional
andfields
are mutually-exclusive options.
include
: Dictionary of additional fields to include in the schema. It isusually better to define fields as class variables, but you may need to use this option, e.g., if your fields are Python keywords. May be an OrderedDict.
exclude
: Tuple or list of fields to exclude in the serialized result.Nested fields can be represented with dot delimiters.
dateformat
: Default format for Date <fields.Date> fields.datetimeformat
: Default format for DateTime <fields.DateTime> fields.timeformat
: Default format for Time <fields.Time> fields.render_module
: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.Defaults to json from the standard library.
ordered
: If True, order serialization output according to theorder in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.
index_errors
: If True, errors dictionaries will include the indexof invalid items in a collection.
load_only
: Tuple or list of fields to exclude from serialized results.dump_only
: Tuple or list of fields to exclude from deserializationunknown
: Whether to exclude, include, or raise an error for unknownfields in the data. Use EXCLUDE, INCLUDE or RAISE.
register
: Whether to register the Schema with marshmallow’s internalclass registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.
- OPTIONS_CLASS
alias of
marshmallow.schema.SchemaOpts
- TYPE_MAPPING: Dict[type, Type[ma_fields.Field]] = {<class 'str'>: <class 'marshmallow.fields.String'>, <class 'bytes'>: <class 'marshmallow.fields.String'>, <class 'datetime.datetime'>: <class 'marshmallow.fields.DateTime'>, <class 'float'>: <class 'marshmallow.fields.Float'>, <class 'bool'>: <class 'marshmallow.fields.Boolean'>, <class 'tuple'>: <class 'marshmallow.fields.Raw'>, <class 'list'>: <class 'marshmallow.fields.Raw'>, <class 'set'>: <class 'marshmallow.fields.Raw'>, <class 'int'>: <class 'marshmallow.fields.Integer'>, <class 'uuid.UUID'>: <class 'marshmallow.fields.UUID'>, <class 'datetime.time'>: <class 'marshmallow.fields.Time'>, <class 'datetime.date'>: <class 'marshmallow.fields.Date'>, <class 'datetime.timedelta'>: <class 'marshmallow.fields.TimeDelta'>, <class 'decimal.Decimal'>: <class 'marshmallow.fields.Decimal'>}
- dump(obj: Any, *, many: bool | None = None)
Serialize an object to native Python data types according to this Schema’s fields.
- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
Serialized data
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.
- dumps(obj: Any, *args, many: bool | None = None, **kwargs)
Same as
dump()
, except return a JSON-encoded string.- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A
json
string
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.
- error_messages: Dict[str, str] = {'unknown': 'Unknown configuration. See https://nitpick.rtfd.io/en/latest/nitpick_section.html.'}
Overrides for default schema-level error messages
- classmethod from_dict(fields: dict[str, ma_fields.Field | type], *, name: str = 'GeneratedSchema') type
Generate a Schema class given a dictionary of fields.
from marshmallow import Schema, fields PersonSchema = Schema.from_dict({"name": fields.Str()}) print(PersonSchema().load({"name": "David"})) # => {'name': 'David'}
Generated schemas are not added to the class registry and therefore cannot be referred to by name in Nested fields.
- Parameters
New in version 3.0.0.
- get_attribute(obj: Any, attr: str, default: Any)
Defines how to pull values from an object to serialize.
New in version 2.0.0.
Changed in version 3.0.0a1: Changed position of
obj
andattr
.
- handle_error(error: marshmallow.exceptions.ValidationError, data: Any, *, many: bool, **kwargs)
Custom error handler function for the schema.
- Parameters
error – The ValidationError raised during (de)serialization.
data – The original input data.
many – Value of
many
on dump or load.partial – Value of
partial
on load.
New in version 2.0.0.
Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.
- load(data: Mapping[str, Any] | Iterable[Mapping[str, Any]], *, many: bool | None = None, partial: bool | types.StrSequenceOrSet | None = None, unknown: str | None = None)
Deserialize a data structure to an object defined by this Schema’s fields.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
- Returns
Deserialized data
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the deserialized data rather than a
(data, errors)
duple. AValidationError
is raised if invalid data are passed.
- loads(json_data: str, *, many: bool | None = None, partial: bool | types.StrSequenceOrSet | None = None, unknown: str | None = None, **kwargs)
Same as
load()
, except it takes a JSON string as input.- Parameters
json_data – A JSON string of the data to deserialize.
many – Whether to deserialize obj as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
- Returns
Deserialized data
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the deserialized data rather than a
(data, errors)
duple. AValidationError
is raised if invalid data are passed.
- on_bind_field(field_name: str, field_obj: marshmallow.fields.Field) None
Hook to modify a field when it is bound to the Schema.
No-op by default.
- opts: SchemaOpts = <marshmallow.schema.SchemaOpts object>
- validate(data: Mapping[str, Any] | Iterable[Mapping[str, Any]], *, many: bool | None = None, partial: bool | types.StrSequenceOrSet | None = None) dict[str, list[str]]
Validate data against the schema, returning a dictionary of validation errors.
- Parameters
data – The data to validate.
many – Whether to validate data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.
- Returns
A dictionary of validation errors.
New in version 1.1.0.
- class nitpick.schemas.NitpickSectionSchema(*, only: types.StrSequenceOrSet | None = None, exclude: types.StrSequenceOrSet = (), many: bool = False, context: dict | None = None, load_only: types.StrSequenceOrSet = (), dump_only: types.StrSequenceOrSet = (), partial: bool | types.StrSequenceOrSet = False, unknown: str | None = None)[source]
Bases:
nitpick.schemas.BaseNitpickSchema
Validation schema for the
[nitpick]
section on the style file.- class Meta
Bases:
object
Options object for a Schema.
Example usage:
class Meta: fields = ("id", "email", "date_created") exclude = ("password", "secret_attribute")
Available options:
fields
: Tuple or list of fields to include in the serialized result.additional
: Tuple or list of fields to include in addition to theexplicitly declared fields.
additional
andfields
are mutually-exclusive options.
include
: Dictionary of additional fields to include in the schema. It isusually better to define fields as class variables, but you may need to use this option, e.g., if your fields are Python keywords. May be an OrderedDict.
exclude
: Tuple or list of fields to exclude in the serialized result.Nested fields can be represented with dot delimiters.
dateformat
: Default format for Date <fields.Date> fields.datetimeformat
: Default format for DateTime <fields.DateTime> fields.timeformat
: Default format for Time <fields.Time> fields.render_module
: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.Defaults to json from the standard library.
ordered
: If True, order serialization output according to theorder in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.
index_errors
: If True, errors dictionaries will include the indexof invalid items in a collection.
load_only
: Tuple or list of fields to exclude from serialized results.dump_only
: Tuple or list of fields to exclude from deserializationunknown
: Whether to exclude, include, or raise an error for unknownfields in the data. Use EXCLUDE, INCLUDE or RAISE.
register
: Whether to register the Schema with marshmallow’s internalclass registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.
- OPTIONS_CLASS
alias of
marshmallow.schema.SchemaOpts
- TYPE_MAPPING: Dict[type, Type[ma_fields.Field]] = {<class 'str'>: <class 'marshmallow.fields.String'>, <class 'bytes'>: <class 'marshmallow.fields.String'>, <class 'datetime.datetime'>: <class 'marshmallow.fields.DateTime'>, <class 'float'>: <class 'marshmallow.fields.Float'>, <class 'bool'>: <class 'marshmallow.fields.Boolean'>, <class 'tuple'>: <class 'marshmallow.fields.Raw'>, <class 'list'>: <class 'marshmallow.fields.Raw'>, <class 'set'>: <class 'marshmallow.fields.Raw'>, <class 'int'>: <class 'marshmallow.fields.Integer'>, <class 'uuid.UUID'>: <class 'marshmallow.fields.UUID'>, <class 'datetime.time'>: <class 'marshmallow.fields.Time'>, <class 'datetime.date'>: <class 'marshmallow.fields.Date'>, <class 'datetime.timedelta'>: <class 'marshmallow.fields.TimeDelta'>, <class 'decimal.Decimal'>: <class 'marshmallow.fields.Decimal'>}
- dump(obj: Any, *, many: bool | None = None)
Serialize an object to native Python data types according to this Schema’s fields.
- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
Serialized data
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.
- dumps(obj: Any, *args, many: bool | None = None, **kwargs)
Same as
dump()
, except return a JSON-encoded string.- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A
json
string
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.
- error_messages: Dict[str, str] = {'unknown': 'Unknown configuration. See https://nitpick.rtfd.io/en/latest/nitpick_section.html.'}
Overrides for default schema-level error messages
- classmethod from_dict(fields: dict[str, ma_fields.Field | type], *, name: str = 'GeneratedSchema') type
Generate a Schema class given a dictionary of fields.
from marshmallow import Schema, fields PersonSchema = Schema.from_dict({"name": fields.Str()}) print(PersonSchema().load({"name": "David"})) # => {'name': 'David'}
Generated schemas are not added to the class registry and therefore cannot be referred to by name in Nested fields.
- Parameters
New in version 3.0.0.
- get_attribute(obj: Any, attr: str, default: Any)
Defines how to pull values from an object to serialize.
New in version 2.0.0.
Changed in version 3.0.0a1: Changed position of
obj
andattr
.
- handle_error(error: marshmallow.exceptions.ValidationError, data: Any, *, many: bool, **kwargs)
Custom error handler function for the schema.
- Parameters
error – The ValidationError raised during (de)serialization.
data – The original input data.
many – Value of
many
on dump or load.partial – Value of
partial
on load.
New in version 2.0.0.
Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.
- load(data: Mapping[str, Any] | Iterable[Mapping[str, Any]], *, many: bool | None = None, partial: bool | types.StrSequenceOrSet | None = None, unknown: str | None = None)
Deserialize a data structure to an object defined by this Schema’s fields.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
- Returns
Deserialized data
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the deserialized data rather than a
(data, errors)
duple. AValidationError
is raised if invalid data are passed.
- loads(json_data: str, *, many: bool | None = None, partial: bool | types.StrSequenceOrSet | None = None, unknown: str | None = None, **kwargs)
Same as
load()
, except it takes a JSON string as input.- Parameters
json_data – A JSON string of the data to deserialize.
many – Whether to deserialize obj as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
- Returns
Deserialized data
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the deserialized data rather than a
(data, errors)
duple. AValidationError
is raised if invalid data are passed.
- on_bind_field(field_name: str, field_obj: marshmallow.fields.Field) None
Hook to modify a field when it is bound to the Schema.
No-op by default.
- opts: SchemaOpts = <marshmallow.schema.SchemaOpts object>
- validate(data: Mapping[str, Any] | Iterable[Mapping[str, Any]], *, many: bool | None = None, partial: bool | types.StrSequenceOrSet | None = None) dict[str, list[str]]
Validate data against the schema, returning a dictionary of validation errors.
- Parameters
data – The data to validate.
many – Whether to validate data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.
- Returns
A dictionary of validation errors.
New in version 1.1.0.
- class nitpick.schemas.NitpickStylesSectionSchema(*, only: types.StrSequenceOrSet | None = None, exclude: types.StrSequenceOrSet = (), many: bool = False, context: dict | None = None, load_only: types.StrSequenceOrSet = (), dump_only: types.StrSequenceOrSet = (), partial: bool | types.StrSequenceOrSet = False, unknown: str | None = None)[source]
Bases:
nitpick.schemas.BaseNitpickSchema
Validation schema for the
[nitpick.styles]
section on the style file.- class Meta
Bases:
object
Options object for a Schema.
Example usage:
class Meta: fields = ("id", "email", "date_created") exclude = ("password", "secret_attribute")
Available options:
fields
: Tuple or list of fields to include in the serialized result.additional
: Tuple or list of fields to include in addition to theexplicitly declared fields.
additional
andfields
are mutually-exclusive options.
include
: Dictionary of additional fields to include in the schema. It isusually better to define fields as class variables, but you may need to use this option, e.g., if your fields are Python keywords. May be an OrderedDict.
exclude
: Tuple or list of fields to exclude in the serialized result.Nested fields can be represented with dot delimiters.
dateformat
: Default format for Date <fields.Date> fields.datetimeformat
: Default format for DateTime <fields.DateTime> fields.timeformat
: Default format for Time <fields.Time> fields.render_module
: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.Defaults to json from the standard library.
ordered
: If True, order serialization output according to theorder in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.
index_errors
: If True, errors dictionaries will include the indexof invalid items in a collection.
load_only
: Tuple or list of fields to exclude from serialized results.dump_only
: Tuple or list of fields to exclude from deserializationunknown
: Whether to exclude, include, or raise an error for unknownfields in the data. Use EXCLUDE, INCLUDE or RAISE.
register
: Whether to register the Schema with marshmallow’s internalclass registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.
- OPTIONS_CLASS
alias of
marshmallow.schema.SchemaOpts
- TYPE_MAPPING: Dict[type, Type[ma_fields.Field]] = {<class 'str'>: <class 'marshmallow.fields.String'>, <class 'bytes'>: <class 'marshmallow.fields.String'>, <class 'datetime.datetime'>: <class 'marshmallow.fields.DateTime'>, <class 'float'>: <class 'marshmallow.fields.Float'>, <class 'bool'>: <class 'marshmallow.fields.Boolean'>, <class 'tuple'>: <class 'marshmallow.fields.Raw'>, <class 'list'>: <class 'marshmallow.fields.Raw'>, <class 'set'>: <class 'marshmallow.fields.Raw'>, <class 'int'>: <class 'marshmallow.fields.Integer'>, <class 'uuid.UUID'>: <class 'marshmallow.fields.UUID'>, <class 'datetime.time'>: <class 'marshmallow.fields.Time'>, <class 'datetime.date'>: <class 'marshmallow.fields.Date'>, <class 'datetime.timedelta'>: <class 'marshmallow.fields.TimeDelta'>, <class 'decimal.Decimal'>: <class 'marshmallow.fields.Decimal'>}
- dump(obj: Any, *, many: bool | None = None)
Serialize an object to native Python data types according to this Schema’s fields.
- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
Serialized data
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.
- dumps(obj: Any, *args, many: bool | None = None, **kwargs)
Same as
dump()
, except return a JSON-encoded string.- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A
json
string
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.
- error_messages: Dict[str, str] = {'unknown': 'Unknown configuration. See https://nitpick.rtfd.io/en/latest/nitpick_section.html#nitpick-styles.'}
Overrides for default schema-level error messages
- classmethod from_dict(fields: dict[str, ma_fields.Field | type], *, name: str = 'GeneratedSchema') type
Generate a Schema class given a dictionary of fields.
from marshmallow import Schema, fields PersonSchema = Schema.from_dict({"name": fields.Str()}) print(PersonSchema().load({"name": "David"})) # => {'name': 'David'}
Generated schemas are not added to the class registry and therefore cannot be referred to by name in Nested fields.
- Parameters
New in version 3.0.0.
- get_attribute(obj: Any, attr: str, default: Any)
Defines how to pull values from an object to serialize.
New in version 2.0.0.
Changed in version 3.0.0a1: Changed position of
obj
andattr
.
- handle_error(error: marshmallow.exceptions.ValidationError, data: Any, *, many: bool, **kwargs)
Custom error handler function for the schema.
- Parameters
error – The ValidationError raised during (de)serialization.
data – The original input data.
many – Value of
many
on dump or load.partial – Value of
partial
on load.
New in version 2.0.0.
Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.
- load(data: Mapping[str, Any] | Iterable[Mapping[str, Any]], *, many: bool | None = None, partial: bool | types.StrSequenceOrSet | None = None, unknown: str | None = None)
Deserialize a data structure to an object defined by this Schema’s fields.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
- Returns
Deserialized data
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the deserialized data rather than a
(data, errors)
duple. AValidationError
is raised if invalid data are passed.
- loads(json_data: str, *, many: bool | None = None, partial: bool | types.StrSequenceOrSet | None = None, unknown: str | None = None, **kwargs)
Same as
load()
, except it takes a JSON string as input.- Parameters
json_data – A JSON string of the data to deserialize.
many – Whether to deserialize obj as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
- Returns
Deserialized data
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the deserialized data rather than a
(data, errors)
duple. AValidationError
is raised if invalid data are passed.
- on_bind_field(field_name: str, field_obj: marshmallow.fields.Field) None
Hook to modify a field when it is bound to the Schema.
No-op by default.
- opts: SchemaOpts = <marshmallow.schema.SchemaOpts object>
- validate(data: Mapping[str, Any] | Iterable[Mapping[str, Any]], *, many: bool | None = None, partial: bool | types.StrSequenceOrSet | None = None) dict[str, list[str]]
Validate data against the schema, returning a dictionary of validation errors.
- Parameters
data – The data to validate.
many – Whether to validate data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.
- Returns
A dictionary of validation errors.
New in version 1.1.0.
nitpick.typedefs module
Type definitions.
nitpick.violations module
Violation codes.
Name inspired by flake8’s violations.
- class nitpick.violations.Fuss(fixed: bool, filename: str, code: int, message: str, suggestion: str = '', lineno: int = 1)[source]
Bases:
object
Nitpick makes a fuss when configuration doesn’t match.
Fields inspired on
SyntaxError
and pyflakes.messages.Message.
- class nitpick.violations.ProjectViolations(value)[source]
Bases:
nitpick.violations.ViolationEnum
Project initialization violations.
- FILE_SHOULD_BE_DELETED = (104, ' should be deleted{extra}')
- MINIMUM_VERSION = (203, "The style file you're using requires {project}>={expected} (you have {actual}). Please upgrade")
- MISSING_FILE = (103, ' should exist{extra}')
- NO_PYTHON_FILE = (102, 'No Python file was found on the root dir and subdir of {root!r}')
- NO_ROOT_DIR = (101, "No root directory detected. Create a configuration file (.nitpick.toml, pyproject.toml) manually, or run 'nitpick init'. See https://nitpick.rtfd.io/en/latest/configuration.html")
- class nitpick.violations.Reporter(info: FileInfo = None, violation_base_code: int = 0)[source]
Bases:
object
Error reporter.
- make_fuss(violation: nitpick.violations.ViolationEnum, suggestion: str = '', fixed=False, **kwargs) nitpick.violations.Fuss [source]
Make a fuss.
Bases:
nitpick.violations.ViolationEnum
Shared violations used by all plugins.
- class nitpick.violations.StyleViolations(value)[source]
Bases:
nitpick.violations.ViolationEnum
Style violations.
- INVALID_CONFIG = (1, ' has an incorrect style. Invalid config:')
- INVALID_DATA_TOOL_NITPICK = (1, ' has an incorrect style. Invalid data in [{section}]:')
- INVALID_TOML = (1, ' has an incorrect style. Invalid TOML{exception}')