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
Nitpick will fail if no style is explicitly configured. Run this command to download and use the opinionated default style file:
nitpick init
You can use it as a template to Configure your own style.
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 .
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.35.0
hooks:
- id: nitpick-suggest
- id: nitpick
There are 4 available hook IDs:
nitpick
andnitpick-fix
both run thenitpick fix
command;nitpick-check
runsnitpick check
;nitpick-suggest
runsnitpick init --fix --suggest
;
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
Run as a MegaLinter plugin
If you use MegaLinter you can run Nitpick as a plugin. Add the following two entries to your .mega-linter.yml
configuration file:
PLUGINS:
- https://raw.githubusercontent.com/andreoliwa/nitpick/v0.35.0/mega-linter-plugin-nitpick/nitpick.megalinter-descriptor.yml
ENABLE_LINTERS:
- NITPICK
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 to 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 to 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]
table 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.
If no style is configured, Nitpick will fail with an error message.
Run nipick init
to create a config file (init: Initialise a configuration file).
To configure your own style, you can either use nitpick init
:
$ nitpick init /path/to/your-style-file.toml
or edit your configuration file and set the style
option:
[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.35.0/nitpick-style.toml"
# or
style = "gh://andreoliwa/nitpick@v0.35.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.35.0/nitpick-style.toml"
Or use the raw GitHub URL directly:
[tool.nitpick]
style = "https://raw.githubusercontent.com/andreoliwa/nitpick/v0.35.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 |
---|---|
markdown
Style URL |
Description |
---|---|
presets
Style URL |
Description |
---|---|
proto
Style URL |
Description |
---|---|
python
Style URL |
Description |
---|---|
Python 3.10 |
|
Python 3.11 |
|
Python 3.12 |
|
Python 3.8 |
|
Python 3.9 |
|
Files that should not exist |
|
shell
Style URL |
Description |
---|---|
toml
Style URL |
Description |
---|---|
The [nitpick] table
The [nitpick] table 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/python38", "styles/poetry"]
The styles will be merged following the sequence in the list. The .toml
extension for each referenced file can be onitted.
Relative references are resolved relative to the URI of the style doument they are included in according to the normal rules of RFC 3986.
E.g. for a style file located at
gh://$GITHUB_TOKEN@foo_dev/bar_project@branchname/styles/foobar.toml
the following
strings all reference the exact same canonical location to include:
[nitpick.styles]
include = [
"foobar.toml",
"../styles/foobar.toml",
"/bar_project@branchname/styles/foobar.toml",
"//$GITHUB_TOKEN@foo_dev/bar_project@branchname/styles/foobar.toml",
]
For style files on the local filesystem, the canonical path (after symbolic links have been resolved) of the style file is used as the base.
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
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.
You can set options through environment variables using the format
NITPICK_command_option
. E.e:NITPICK_CHECK_VERBOSE=3 nitpick check
. For more details on how this works, see the Click documentation about CLI options.
If you use Git, you can review the files before committing.
The available commands are described below.
Suggest styles based on project files
You can use the nitpick init --suggest
command to suggest styles based on the files in your project.
Nitpick will scan the files starting from the project root, skipping the ones ignored by Git, and suggest the styles that match the file types.
By default, it will suggest the styles from the built-in library. You can use the --library
option to scan a custom directory with styles.
The directory structure of your custom library should be the same as the built-in library: <root_library_dir>/<file_type>/<your_style_name>.toml
.
file_type
can be any tag reported by the pre-commit/identify library (e.g.python
,yaml
,markdown
, etc.);use the special type
any
for styles that apply to all file types (e.g. trim trailing whitespace).
The --suggest` command will display what would be changed. To apply these changes and autofix the config, run with the ``--fix
option.
To ignore styles, add them to the [tool.nitpick] ignore_styles
key on the config file.
Nitpick will consider the following Git ignore files:
.gitignore
on the project root;a global ignore file configured by
git config --get core.excludesFile
.
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 or update the [tool.nitpick] table in the configuration...
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] [STYLE_URLS]...
Create or update the [tool.nitpick] table in the configuration file.
Options:
-f, --fix Autofix the files changed by the command;
otherwise, just print what would be done
-s, --suggest Suggest styles based on the extension of project
files (skipping Git ignored files)
-l, --library DIRECTORY Library dir to scan for style files (implies
--suggest); if not provided, uses the built-in
style library
--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.
Missing rev
key when using the default pre-commit
styles
If you’re using the default pre-commit
styles, you might get this error:
An error has occurred: InvalidConfigError:
==> File .pre-commit-config.yaml
==> At Config()
==> At key: repos
==> At Repository(repo='https://github.com/PyCQA/bandit')
=====> Missing required key: rev
Check the log at /Users/your-name/.cache/pre-commit/pre-commit.log
This happens because the default styles don’t have a rev
key.
Currently, this is not possible because the pre-commit plugin doesn’t support it.
To solve this, you can run pre-commit autoupdate
to update the styles to the latest version, as recommended in the official docs.
For more details, check out this comment on the GitHub issue.
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[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[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: PathOrStr | None = None, offline: bool | None = None) Nitpick [source]
Initialize attributes of the singleton.
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
nitpick.plugins.base module
Base class for file checkers.
- class nitpick.plugins.base.NitpickPlugin(info: FileInfo, expected_config: JsonDict, 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[Fuss] [source]
Enforce rules for this file. It must be overridden by inherited classes if needed.
- filename = ''
- identify_tags: ClassVar = {}
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() 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
).
nitpick.plugins.info module
Info needed by the plugins.
nitpick.plugins.ini module
INI files.
- class nitpick.plugins.ini.IniPlugin(info: FileInfo, expected_config: JsonDict, autofix=False)[source]
Bases:
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[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[Fuss] [source]
Enforce sections and keys with comma-separated values.
The values might contain spaces.
- enforce_rules() Iterator[Fuss] [source]
Enforce rules on missing sections and missing key/value pairs in an INI file.
- expected_config: JsonDict
- file_path: Path
- filename = ''
- static get_example_cfg(parser: 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: ClassVar = {'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() 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, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]
Bases:
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[nitpick.plugins.base.NitpickPlugin] [source]
Handle INI files.
nitpick.plugins.json module
JSON files.
- class nitpick.plugins.json.JsonFileSchema(*, only: Sequence[str] | AbstractSet[str] | None = None, exclude: Sequence[str] | AbstractSet[str] = (), many: bool = False, context: dict | None = None, load_only: Sequence[str] | AbstractSet[str] = (), dump_only: Sequence[str] | AbstractSet[str] = (), partial: bool | Sequence[str] | AbstractSet[str] | None = None, unknown: str | None = None)[source]
Bases:
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, 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
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, marshmallow.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: 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 | Sequence[str] | AbstractSet[str] | 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 | Sequence[str] | AbstractSet[str] | 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: Field) None
Hook to modify a field when it is bound to the Schema.
No-op by default.
- opts: SchemaOpts = <marshmallow.schema.SchemaOpts object>
- set_class
alias of
OrderedSet
- validate(data: Mapping[str, Any] | Iterable[Mapping[str, Any]], *, many: bool | None = None, partial: bool | Sequence[str] | AbstractSet[str] | 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: FileInfo, expected_config: JsonDict, autofix=False)[source]
Bases:
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.
- expected_config: JsonDict
- file_path: Path
- filename = ''
- identify_tags: ClassVar = {'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() 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
JsonFileSchema
- nitpick.plugins.json.can_handle(info: FileInfo) type[NitpickPlugin] | None [source]
Handle JSON files.
- nitpick.plugins.json.plugin_class() type[nitpick.plugins.base.NitpickPlugin] [source]
Handle JSON files.
nitpick.plugins.text module
Text files.
- class nitpick.plugins.text.TextItemSchema(*, only: Sequence[str] | AbstractSet[str] | None = None, exclude: Sequence[str] | AbstractSet[str] = (), many: bool = False, context: dict | None = None, load_only: Sequence[str] | AbstractSet[str] = (), dump_only: Sequence[str] | AbstractSet[str] = (), partial: bool | Sequence[str] | AbstractSet[str] | None = None, unknown: str | None = None)[source]
Bases:
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, 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
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, marshmallow.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: 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 | Sequence[str] | AbstractSet[str] | 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 | Sequence[str] | AbstractSet[str] | 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: Field) None
Hook to modify a field when it is bound to the Schema.
No-op by default.
- opts: SchemaOpts = <marshmallow.schema.SchemaOpts object>
- set_class
alias of
OrderedSet
- validate(data: Mapping[str, Any] | Iterable[Mapping[str, Any]], *, many: bool | None = None, partial: bool | Sequence[str] | AbstractSet[str] | 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: FileInfo, expected_config: JsonDict, autofix=False)[source]
Bases:
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"
- expected_config: JsonDict
- file_path: Path
- filename = ''
- identify_tags: ClassVar = {'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() SpecialConfig
Create a predefined special configuration for this plugin.
Each plugin can override this method.
- skip_empty_suggestion = True
- validation_schema
alias of
TextSchema
- class nitpick.plugins.text.TextSchema(*, only: Sequence[str] | AbstractSet[str] | None = None, exclude: Sequence[str] | AbstractSet[str] = (), many: bool = False, context: dict | None = None, load_only: Sequence[str] | AbstractSet[str] = (), dump_only: Sequence[str] | AbstractSet[str] = (), partial: bool | Sequence[str] | AbstractSet[str] | None = None, unknown: str | None = None)[source]
Bases:
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, 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
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, marshmallow.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: 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 | Sequence[str] | AbstractSet[str] | 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 | Sequence[str] | AbstractSet[str] | 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: Field) None
Hook to modify a field when it is bound to the Schema.
No-op by default.
- opts: SchemaOpts = <marshmallow.schema.SchemaOpts object>
- set_class
alias of
OrderedSet
- validate(data: Mapping[str, Any] | Iterable[Mapping[str, Any]], *, many: bool | None = None, partial: bool | Sequence[str] | AbstractSet[str] | 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, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]
Bases:
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[nitpick.plugins.base.NitpickPlugin] [source]
Handle text files.
nitpick.plugins.toml module
TOML files.
- class nitpick.plugins.toml.TomlPlugin(info: FileInfo, expected_config: JsonDict, autofix=False)[source]
Bases:
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[Fuss] [source]
Enforce rules for missing key/value pairs in the TOML file.
- expected_config: JsonDict
- file_path: Path
- filename = ''
- identify_tags: ClassVar = {'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() SpecialConfig
Create a predefined special configuration for this plugin.
Each plugin can override this method.
- report(violation: ViolationEnum, document: TOMLDocument | None, change: TomlDoc | None, replacement: TomlDoc | None = 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[nitpick.plugins.base.NitpickPlugin] [source]
Handle TOML files.
nitpick.plugins.yaml module
YAML files.
- class nitpick.plugins.yaml.YamlPlugin(info: FileInfo, expected_config: JsonDict, autofix=False)[source]
Bases:
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.- expected_config: JsonDict
- file_path: Path
- filename = ''
- identify_tags: ClassVar = {'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() 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[nitpick.plugins.base.NitpickPlugin] [source]
Handle YAML files.
nitpick.resources package
A library of Nitpick styles.
Building blocks that can be combined and reused.
Subpackages
nitpick.resources.any package
Styles for any language.
nitpick.resources.javascript package
Styles for JavaScript.
nitpick.resources.kotlin package
Styles for Kotlin.
nitpick.resources.markdown package
Styles for Markdown files.
nitpick.resources.presets package
Style presets.
nitpick.resources.proto package
Styles for Protobuf files.
nitpick.resources.python package
Styles for Python.
nitpick.resources.shell package
Styles for shell scripts.
nitpick.resources.toml package
Styles for TOML files.
Submodules
nitpick.blender module
Dictionary blender and configuration file formats.
- class nitpick.blender.BaseDoc(*, path: Path | str | None = None, string: str | None = None, obj: Dict[str, Any] | None = 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: TBaseDoc, expected: JsonDict, special_config: SpecialConfig)[source]
Bases:
object
A comparison between two dictionaries, computing missing items and differences.
- class nitpick.blender.ElementDetail(data: Dict[str, Any] | str | int | float | CommentedMap | List[Any], 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.
- class nitpick.blender.InlineTableTomlDecoder(_dict=<class 'dict'>)[source]
Bases:
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: Path | str | None = None, string: str | None = None, obj: Dict[str, Any] | None = None)[source]
Bases:
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: List[Any] | CommentedSeq, elements: list[nitpick.blender.ElementDetail])[source]
Bases:
object
Detailed info about a list.
Method generated by attrs for class ListDetail.
- elements: list[nitpick.blender.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:
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.
- compose(stream: Path | Any) Any
Parse the first YAML document in a stream and produce the corresponding representation tree.
- compose_all(stream: Path | Any) Any
Parse all YAML documents in a stream and produce corresponding representation trees.
- 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.
- get_constructor_parser(stream: Any) Any
the old cyaml needs special setup, and therefore the stream
- load(stream: Path | Any) 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
- loads(string: str)[source]
Load YAML from a string… that unusual use case in a world of files only.
- 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__’])
- 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
- serialize(node: Any, stream: Any | None) Any
Serialize a representation tree into a YAML stream. If stream is None, return the produced string instead.
- class nitpick.blender.TomlDoc(*, path: Path | str | None = None, string: str | None = None, obj: Dict[str, Any] | None = None, use_tomlkit=False)[source]
Bases:
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: Path | str | None = None, string: str | None = None, obj: Dict[str, Any] | None = None)[source]
Bases:
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: 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: CommentedSeq | 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 = 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.compat module
Handle import compatibility issues.
nitpick.config module
Special configurations.
- class nitpick.config.OverridableConfig(from_plugin: Dict[str, Any] = _Nothing.NOTHING, from_style: Dict[str, Any] = _Nothing.NOTHING, value: Dict[str, Any] = _Nothing.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: OverridableConfig = _Nothing.NOTHING)[source]
Bases:
object
Special configurations for plugins.
Method generated by attrs for class SpecialConfig.
- list_keys: OverridableConfig
nitpick.constants module
Constants.
- class nitpick.constants.CachingEnum(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]
Bases:
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.
- as_integer_ratio()
Return integer ratio.
Return a pair of integers, whose ratio is exactly equal to the original int and with a positive denominator.
>>> (10).as_integer_ratio() (10, 1) >>> (-10).as_integer_ratio() (-10, 1) >>> (0).as_integer_ratio() (0, 1)
- bit_count()
Number of ones in the binary representation of the absolute value of self.
Also known as the population count.
>>> bin(13) '0b1101' >>> (13).bit_count() 3
- bit_length()
Number of bits necessary to represent self in binary.
>>> bin(37) '0b100101' >>> (37).bit_length() 6
- conjugate()
Returns self, the complex conjugate of any int.
- denominator
the denominator of a rational number in lowest terms
- from_bytes(byteorder='big', *, signed=False)
Return the integer represented by the given array of bytes.
- bytes
Holds the array of bytes to convert. The argument must either support the buffer protocol or be an iterable object producing bytes. Bytes and bytearray are examples of built-in objects that support the buffer protocol.
- byteorder
The byte order used to represent the integer. If byteorder is ‘big’, the most significant byte is at the beginning of the byte array. If byteorder is ‘little’, the most significant byte is at the end of the byte array. To request the native byte order of the host system, use `sys.byteorder’ as the byte order value. Default is to use ‘big’.
- signed
Indicates whether two’s complement is used to represent the integer.
- imag
the imaginary part of a complex number
- numerator
the numerator of a rational number in lowest terms
- real
the real part of a complex number
- to_bytes(length=1, byteorder='big', *, signed=False)
Return an array of bytes representing an integer.
- length
Length of bytes object to use. An OverflowError is raised if the integer is not representable with the given number of bytes. Default is length 1.
- byteorder
The byte order used to represent the integer. If byteorder is ‘big’, the most significant byte is at the beginning of the byte array. If byteorder is ‘little’, the most significant byte is at the end of the byte array. To request the native byte order of the host system, use `sys.byteorder’ as the byte order value. Default is to use ‘big’.
- signed
Determines whether two’s complement is used to represent the integer. If signed is False and a negative integer is given, an OverflowError is raised.
nitpick.core module
The Nitpick application and project-related utilities.
- class nitpick.core.Configuration(file: Path, doc: TOMLDocument, table: Table, styles: Array, dont_suggest: Array, cache: str)[source]
Bases:
object
Configuration read from the
[tool.nitpick]
table from one of theCONFIG_FILES
.- doc: TOMLDocument
- dont_suggest: Array
- styles: Array
- table: Table
- 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[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[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: PathOrStr | None = None, offline: bool | None = None) Nitpick [source]
Initialize attributes of the singleton.
- class nitpick.core.Project(root: PathOrStr | None = None)[source]
Bases:
object
A project to be nitpicked.
- property plugin_manager: PluginManager
Load all defined plugins.
- read_configuration() Configuration [source]
Return the
[tool.nitpick]
table from the configuration file.Optionally, validate it against a Marshmallow schema.
- class nitpick.core.ToolNitpickSectionSchema(*, only: Sequence[str] | AbstractSet[str] | None = None, exclude: Sequence[str] | AbstractSet[str] = (), many: bool = False, context: dict | None = None, load_only: Sequence[str] | AbstractSet[str] = (), dump_only: Sequence[str] | AbstractSet[str] = (), partial: bool | Sequence[str] | AbstractSet[str] | None = None, unknown: str | None = None)[source]
Bases:
BaseNitpickSchema
Validation schema for the
[tool.nitpick]
table 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, 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
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, marshmallow.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: 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 | Sequence[str] | AbstractSet[str] | 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 | Sequence[str] | AbstractSet[str] | 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: Field) None
Hook to modify a field when it is bound to the Schema.
No-op by default.
- opts: SchemaOpts = <marshmallow.schema.SchemaOpts object>
- set_class
alias of
OrderedSet
- validate(data: Mapping[str, Any] | Iterable[Mapping[str, Any]], *, many: bool | None = None, partial: bool | Sequence[str] | AbstractSet[str] | 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.core.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.core.find_main_python_file(root_dir: Path) 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.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: Fuss | list[Fuss])[source]
Bases:
Exception
Quit complaining and exit the application.
- add_note()
Exception.add_note(note) – add a note to the exception
- 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:
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) 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:
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) 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:
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) 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: ~marshmallow.base.SchemaABC | type | str | dict[str, marshmallow.fields.Field | type] | ~typing.Callable[[], ~marshmallow.base.SchemaABC | dict[str, marshmallow.fields.Field | type]], *, dump_default: ~typing.Any = <marshmallow.missing>, default: ~typing.Any = <marshmallow.missing>, only: ~typing.Sequence[str] | ~typing.AbstractSet[str] | None = None, exclude: ~typing.Sequence[str] | ~typing.AbstractSet[str] = (), many: bool = False, unknown: str | None = None, **kwargs)[source]
Bases:
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) 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:
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) 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.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.
- build_flake8_error(obj: Fuss) Tuple[int, int, str, Type] [source]
Return a flake8 error from a fuss.
- name = 'nitpick'
- static parse_options(option_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.35.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.get_global_gitignore_path() Path | None [source]
Get the path to the global Git ignore file.
- nitpick.generic.glob_files(dir_: Path, file_patterns: Iterable[str]) set[pathlib.Path] [source]
Search a directory looking for file patterns.
- nitpick.generic.glob_non_ignored_files(root_dir: Path, pattern: str = '**/*') Iterable[Path] [source]
Glob all files in the root dir that are not ignored by Git.
- 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.url_to_python_path(url: furl) Path
Convert the segments of a file URL to a path.
nitpick.schemas module
Marshmallow schemas.
- class nitpick.schemas.BaseNitpickSchema(*, only: Sequence[str] | AbstractSet[str] | None = None, exclude: Sequence[str] | AbstractSet[str] = (), many: bool = False, context: dict | None = None, load_only: Sequence[str] | AbstractSet[str] = (), dump_only: Sequence[str] | AbstractSet[str] = (), partial: bool | Sequence[str] | AbstractSet[str] | None = None, unknown: str | None = None)[source]
Bases:
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, 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
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, marshmallow.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: 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 | Sequence[str] | AbstractSet[str] | 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 | Sequence[str] | AbstractSet[str] | 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: Field) None
Hook to modify a field when it is bound to the Schema.
No-op by default.
- opts: SchemaOpts = <marshmallow.schema.SchemaOpts object>
- set_class
alias of
OrderedSet
- validate(data: Mapping[str, Any] | Iterable[Mapping[str, Any]], *, many: bool | None = None, partial: bool | Sequence[str] | AbstractSet[str] | 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: Sequence[str] | AbstractSet[str] | None = None, exclude: Sequence[str] | AbstractSet[str] = (), many: bool = False, context: dict | None = None, load_only: Sequence[str] | AbstractSet[str] = (), dump_only: Sequence[str] | AbstractSet[str] = (), partial: bool | Sequence[str] | AbstractSet[str] | None = None, unknown: str | None = None)[source]
Bases:
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, 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
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, marshmallow.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: 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 | Sequence[str] | AbstractSet[str] | 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 | Sequence[str] | AbstractSet[str] | 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: Field) None
Hook to modify a field when it is bound to the Schema.
No-op by default.
- opts: SchemaOpts = <marshmallow.schema.SchemaOpts object>
- set_class
alias of
OrderedSet
- validate(data: Mapping[str, Any] | Iterable[Mapping[str, Any]], *, many: bool | None = None, partial: bool | Sequence[str] | AbstractSet[str] | 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: Sequence[str] | AbstractSet[str] | None = None, exclude: Sequence[str] | AbstractSet[str] = (), many: bool = False, context: dict | None = None, load_only: Sequence[str] | AbstractSet[str] = (), dump_only: Sequence[str] | AbstractSet[str] = (), partial: bool | Sequence[str] | AbstractSet[str] | None = None, unknown: str | None = None)[source]
Bases:
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, 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
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
- exclude: set[Any] | MutableSet[Any]
- classmethod from_dict(fields: dict[str, marshmallow.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: 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 | Sequence[str] | AbstractSet[str] | 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 | Sequence[str] | AbstractSet[str] | 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: Field) None
Hook to modify a field when it is bound to the Schema.
No-op by default.
- opts: SchemaOpts = <marshmallow.schema.SchemaOpts object>
- set_class
alias of
OrderedSet
- validate(data: Mapping[str, Any] | Iterable[Mapping[str, Any]], *, many: bool | None = None, partial: bool | Sequence[str] | AbstractSet[str] | 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: Sequence[str] | AbstractSet[str] | None = None, exclude: Sequence[str] | AbstractSet[str] = (), many: bool = False, context: dict | None = None, load_only: Sequence[str] | AbstractSet[str] = (), dump_only: Sequence[str] | AbstractSet[str] = (), partial: bool | Sequence[str] | AbstractSet[str] | None = None, unknown: str | None = None)[source]
Bases:
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, 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
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
- exclude: set[Any] | MutableSet[Any]
- classmethod from_dict(fields: dict[str, marshmallow.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: 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 | Sequence[str] | AbstractSet[str] | 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 | Sequence[str] | AbstractSet[str] | 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: Field) None
Hook to modify a field when it is bound to the Schema.
No-op by default.
- opts: SchemaOpts = <marshmallow.schema.SchemaOpts object>
- set_class
alias of
OrderedSet
- validate(data: Mapping[str, Any] | Iterable[Mapping[str, Any]], *, many: bool | None = None, partial: bool | Sequence[str] | AbstractSet[str] | 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: Sequence[str] | AbstractSet[str] | None = None, exclude: Sequence[str] | AbstractSet[str] = (), many: bool = False, context: dict | None = None, load_only: Sequence[str] | AbstractSet[str] = (), dump_only: Sequence[str] | AbstractSet[str] = (), partial: bool | Sequence[str] | AbstractSet[str] | None = None, unknown: str | None = None)[source]
Bases:
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, 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
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
- exclude: set[Any] | MutableSet[Any]
- classmethod from_dict(fields: dict[str, marshmallow.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: 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 | Sequence[str] | AbstractSet[str] | 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 | Sequence[str] | AbstractSet[str] | 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: Field) None
Hook to modify a field when it is bound to the Schema.
No-op by default.
- opts: SchemaOpts = <marshmallow.schema.SchemaOpts object>
- set_class
alias of
OrderedSet
- validate(data: Mapping[str, Any] | Iterable[Mapping[str, Any]], *, many: bool | None = None, partial: bool | Sequence[str] | AbstractSet[str] | 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: Sequence[str] | AbstractSet[str] | None = None, exclude: Sequence[str] | AbstractSet[str] = (), many: bool = False, context: dict | None = None, load_only: Sequence[str] | AbstractSet[str] = (), dump_only: Sequence[str] | AbstractSet[str] = (), partial: bool | Sequence[str] | AbstractSet[str] | None = None, unknown: str | None = None)[source]
Bases:
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, 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
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
- exclude: set[Any] | MutableSet[Any]
- classmethod from_dict(fields: dict[str, marshmallow.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: 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 | Sequence[str] | AbstractSet[str] | 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 | Sequence[str] | AbstractSet[str] | 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: Field) None
Hook to modify a field when it is bound to the Schema.
No-op by default.
- opts: SchemaOpts = <marshmallow.schema.SchemaOpts object>
- set_class
alias of
OrderedSet
- validate(data: Mapping[str, Any] | Iterable[Mapping[str, Any]], *, many: bool | None = None, partial: bool | Sequence[str] | AbstractSet[str] | 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: Sequence[str] | AbstractSet[str] | None = None, exclude: Sequence[str] | AbstractSet[str] = (), many: bool = False, context: dict | None = None, load_only: Sequence[str] | AbstractSet[str] = (), dump_only: Sequence[str] | AbstractSet[str] = (), partial: bool | Sequence[str] | AbstractSet[str] | None = None, unknown: str | None = None)[source]
Bases:
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, 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
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
- exclude: set[Any] | MutableSet[Any]
- classmethod from_dict(fields: dict[str, marshmallow.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: 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 | Sequence[str] | AbstractSet[str] | 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 | Sequence[str] | AbstractSet[str] | 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: Field) None
Hook to modify a field when it is bound to the Schema.
No-op by default.
- opts: SchemaOpts = <marshmallow.schema.SchemaOpts object>
- set_class
alias of
OrderedSet
- validate(data: Mapping[str, Any] | Iterable[Mapping[str, Any]], *, many: bool | None = None, partial: bool | Sequence[str] | AbstractSet[str] | 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.style module
Style parsing and merging.
- class nitpick.style.BuiltinStyle(*, formatted: str, path_from_resources_root: str)[source]
Bases:
object
A built-in style file in TOML format.
Method generated by attrs for class BuiltinStyle.
- class nitpick.style.ConfigValidator(project: Project)[source]
Bases:
object
Validate a nitpick configuration.
- class nitpick.style.FileFetcher(session: ~requests_cache.session.CachedSession | None = None, protocols: tuple[str, ...] = (<Scheme.FILE: 'file'>, ), domains: tuple[str, ...] = ())[source]
Bases:
StyleFetcher
Fetch a style from a local file.
- normalize(url: furl) furl
Normalize a URL.
Produces a canonical URL, meant to be used to uniquely identify a style resource.
The base name has .toml appended if not already ending in that extension
Individual fetchers can further normalize the path and scheme.
- class nitpick.style.GitHubFetcher(session: ~requests_cache.session.CachedSession | None = None, protocols: tuple[str, ...] = (<Scheme.GH: 'gh'>, <Scheme.GITHUB: 'github'>), domains: tuple[str, ...] = ('github.com', ))[source]
Bases:
HttpFetcher
Fetch styles from GitHub repositories.
- normalize(url: furl) furl
Normalize a URL.
Produces a canonical URL, meant to be used to uniquely identify a style resource.
The base name has .toml appended if not already ending in that extension
Individual fetchers can further normalize the path and scheme.
- class nitpick.style.GitHubURL(owner: str, repository: str, git_reference: str, path: tuple[str, ...] = (), auth_token: str | None = None, query_params: tuple[tuple[str, str], ...] | None = None)[source]
Bases:
object
Represent a GitHub URL, created from a URL or from its parts.
- property api_url: furl
API URL for this repo.
- classmethod from_furl(url: furl) GitHubURL [source]
Create an instance from a parsed URL in any accepted format.
See the code for
test_parsing_github_urls()
for more examples.
- property git_reference_or_default: str
Return the Git reference if informed, or return the default branch.
- property long_protocol_url: furl
Long protocol URL (
github
).
- property raw_content_url: furl
Raw content URL for this path.
- property short_protocol_url: furl
Short protocol URL (
gh
).
- property token: str | None
Token encoded in this URL.
If present and it starts with a
$
, it will be replaced with the value of the environment corresponding to the remaining part of the string.
- property url: furl
Default URL built from attributes.
- class nitpick.style.HttpFetcher(session: ~requests_cache.session.CachedSession | None = None, protocols: tuple[str, ...] = (<Scheme.HTTP: 'http'>, <Scheme.HTTPS: 'https'>), domains: tuple[str, ...] = ())[source]
Bases:
StyleFetcher
Fetch a style from an http/https server.
- normalize(url: furl) furl
Normalize a URL.
Produces a canonical URL, meant to be used to uniquely identify a style resource.
The base name has .toml appended if not already ending in that extension
Individual fetchers can further normalize the path and scheme.
- class nitpick.style.PythonPackageFetcher(session: ~requests_cache.session.CachedSession | None = None, protocols: tuple[str, ...] = (<Scheme.PY: 'py'>, <Scheme.PYPACKAGE: 'pypackage'>), domains: tuple[str, ...] = ())[source]
Bases:
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
.- normalize(url: furl) furl
Normalize a URL.
Produces a canonical URL, meant to be used to uniquely identify a style resource.
The base name has .toml appended if not already ending in that extension
Individual fetchers can further normalize the path and scheme.
- class nitpick.style.PythonPackageURL(import_path: str, resource_name: str)[source]
Bases:
object
Represent a resource file in installed Python package.
- classmethod from_furl(url: furl) PythonPackageURL [source]
Create an instance from a parsed URL in any accepted format.
See the code for
test_parsing_python_package_urls()
for more examples.
- class nitpick.style.Scheme(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]
Bases:
LowercaseStrEnum
URL schemes.
- FILE = 'file'
- GH = 'gh'
- GITHUB = 'github'
- HTTP = 'http'
- HTTPS = 'https'
- PY = 'py'
- PYPACKAGE = 'pypackage'
- capitalize()
Return a capitalized version of the string.
More specifically, make the first character have upper case and the rest lower case.
- casefold()
Return a version of the string suitable for caseless comparisons.
- center(width, fillchar=' ', /)
Return a centered string of length width.
Padding is done using the specified fill character (default is a space).
- count(sub[, start[, end]]) int
Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation.
- encode(encoding='utf-8', errors='strict')
Encode the string using the codec registered for encoding.
- encoding
The encoding in which to encode the string.
- errors
The error handling scheme to use for encoding errors. The default is ‘strict’ meaning that encoding errors raise a UnicodeEncodeError. Other possible values are ‘ignore’, ‘replace’ and ‘xmlcharrefreplace’ as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors.
- endswith(suffix[, start[, end]]) bool
Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try.
- expandtabs(tabsize=8)
Return a copy where all tab characters are expanded using spaces.
If tabsize is not given, a tab size of 8 characters is assumed.
- find(sub[, start[, end]]) int
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Return -1 on failure.
- format(*args, **kwargs) str
Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces (‘{’ and ‘}’).
- format_map(mapping) str
Return a formatted version of S, using substitutions from mapping. The substitutions are identified by braces (‘{’ and ‘}’).
- index(sub[, start[, end]]) int
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Raises ValueError when the substring is not found.
- isalnum()
Return True if the string is an alpha-numeric string, False otherwise.
A string is alpha-numeric if all characters in the string are alpha-numeric and there is at least one character in the string.
- isalpha()
Return True if the string is an alphabetic string, False otherwise.
A string is alphabetic if all characters in the string are alphabetic and there is at least one character in the string.
- isascii()
Return True if all characters in the string are ASCII, False otherwise.
ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too.
- isdecimal()
Return True if the string is a decimal string, False otherwise.
A string is a decimal string if all characters in the string are decimal and there is at least one character in the string.
- isdigit()
Return True if the string is a digit string, False otherwise.
A string is a digit string if all characters in the string are digits and there is at least one character in the string.
- isidentifier()
Return True if the string is a valid Python identifier, False otherwise.
Call keyword.iskeyword(s) to test whether string s is a reserved identifier, such as “def” or “class”.
- islower()
Return True if the string is a lowercase string, False otherwise.
A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.
- isnumeric()
Return True if the string is a numeric string, False otherwise.
A string is numeric if all characters in the string are numeric and there is at least one character in the string.
- isprintable()
Return True if the string is printable, False otherwise.
A string is printable if all of its characters are considered printable in repr() or if it is empty.
- isspace()
Return True if the string is a whitespace string, False otherwise.
A string is whitespace if all characters in the string are whitespace and there is at least one character in the string.
- istitle()
Return True if the string is a title-cased string, False otherwise.
In a title-cased string, upper- and title-case characters may only follow uncased characters and lowercase characters only cased ones.
- isupper()
Return True if the string is an uppercase string, False otherwise.
A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string.
- join(iterable, /)
Concatenate any number of strings.
The string whose method is called is inserted in between each given string. The result is returned as a new string.
Example: ‘.’.join([‘ab’, ‘pq’, ‘rs’]) -> ‘ab.pq.rs’
- ljust(width, fillchar=' ', /)
Return a left-justified string of length width.
Padding is done using the specified fill character (default is a space).
- lower()
Return a copy of the string converted to lowercase.
- lstrip(chars=None, /)
Return a copy of the string with leading whitespace removed.
If chars is given and not None, remove characters in chars instead.
- static maketrans()
Return a translation table usable for str.translate().
If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.
- partition(sep, /)
Partition the string into three parts using the given separator.
This will search for the separator in the string. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.
If the separator is not found, returns a 3-tuple containing the original string and two empty strings.
- removeprefix(prefix, /)
Return a str with the given prefix string removed if present.
If the string starts with the prefix string, return string[len(prefix):]. Otherwise, return a copy of the original string.
- removesuffix(suffix, /)
Return a str with the given suffix string removed if present.
If the string ends with the suffix string and that suffix is not empty, return string[:-len(suffix)]. Otherwise, return a copy of the original string.
- replace(old, new, count=-1, /)
Return a copy with all occurrences of substring old replaced by new.
- count
Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences.
If the optional argument count is given, only the first count occurrences are replaced.
- rfind(sub[, start[, end]]) int
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Return -1 on failure.
- rindex(sub[, start[, end]]) int
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Raises ValueError when the substring is not found.
- rjust(width, fillchar=' ', /)
Return a right-justified string of length width.
Padding is done using the specified fill character (default is a space).
- rpartition(sep, /)
Partition the string into three parts using the given separator.
This will search for the separator in the string, starting at the end. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.
If the separator is not found, returns a 3-tuple containing two empty strings and the original string.
- rsplit(sep=None, maxsplit=-1)
Return a list of the substrings in the string, using sep as the separator string.
- sep
The separator used to split the string.
When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.
- maxsplit
Maximum number of splits (starting from the left). -1 (the default value) means no limit.
Splitting starts at the end of the string and works to the front.
- rstrip(chars=None, /)
Return a copy of the string with trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
- split(sep=None, maxsplit=-1)
Return a list of the substrings in the string, using sep as the separator string.
- sep
The separator used to split the string.
When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.
- maxsplit
Maximum number of splits (starting from the left). -1 (the default value) means no limit.
Note, str.split() is mainly useful for data that has been intentionally delimited. With natural text that includes punctuation, consider using the regular expression module.
- splitlines(keepends=False)
Return a list of the lines in the string, breaking at line boundaries.
Line breaks are not included in the resulting list unless keepends is given and true.
- startswith(prefix[, start[, end]]) bool
Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try.
- strip(chars=None, /)
Return a copy of the string with leading and trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
- swapcase()
Convert uppercase characters to lowercase and lowercase characters to uppercase.
- title()
Return a version of the string where each word is titlecased.
More specifically, words start with uppercased characters and all remaining cased characters have lower case.
- translate(table, /)
Replace each character in the string using the given translation table.
- table
Translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, strings, or None.
The table must implement lookup/indexing via __getitem__, for instance a dictionary or list. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted.
- upper()
Return a copy of the string converted to uppercase.
- zfill(width, /)
Pad a numeric string with zeros on the left, to fill a field of the given width.
The string is never truncated.
- class nitpick.style.StyleFetcher(session: CachedSession | None = None, protocols: tuple[str, ...] = (), domains: tuple[str, ...] = ())[source]
Bases:
object
Base class of all fetchers, it encapsulates get/fetch from a specific source.
- normalize(url: furl) furl [source]
Normalize a URL.
Produces a canonical URL, meant to be used to uniquely identify a style resource.
The base name has .toml appended if not already ending in that extension
Individual fetchers can further normalize the path and scheme.
- class nitpick.style.StyleFetcherManager(offline: bool, cache_dir: Path, cache_option: str)[source]
Bases:
object
Manager that controls which fetcher to be used given a protocol.
- fetch(url: furl) str | None [source]
Determine which fetcher to be used and fetch from it.
Returns None when offline is True and the fetcher would otherwise require a connection.
- fetchers: dict[str, nitpick.style.StyleFetcher]
- normalize_url(url: str | furl, base: furl) furl [source]
Normalize a style URL.
The URL is made absolute against base, then passed to individual fetchers to produce a canonical version of the URL.
- session: CachedSession
- class nitpick.style.StyleManager(project: Project, offline: bool, cache_option: str)[source]
Bases:
object
Include styles recursively from one another.
- property cache_dir: 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: Sequence[str], base: str | None = None) Iterator[Fuss] [source]
Find the initial style(s) and include them.
base is the URL for the source of the initial styles, and is used to resolve relative references. If omitted, defaults to the project root.
- static get_default_style_url(github=False) furl [source]
Return the URL of the default style/preset.
- include_multiple_styles(chosen_styles: Iterable[furl]) Iterator[Fuss] [source]
Include a list of styles (or just one) into this style tree.
- load_fixed_name_plugins() set[type[NitpickPlugin]] [source]
Separate classes with fixed file names from classes with dynamic files names.
- nitpick.style.github_default_branch(api_url: str, *, token: str | None = None) str [source]
Get the default branch from the GitHub repo using the API.
For now, for URLs without an authorization token embedded, 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.
- nitpick.style.parse_cache_option(cache_option: str) tuple[nitpick.constants.CachingEnum, datetime.timedelta | int] [source]
Parse the cache option provided on pyproject.toml.
If no cache is provided or is invalid, the default is one hour.
nitpick.tomlkit_ext module
Extensions for the tomlkit package, with drop-in replacement functions and classes.
Eventually, some of the code here should/could be proposed as pull requests to the original package.
- nitpick.tomlkit_ext.load(file_pointer: IO[str] | IO[bytes] | Path) TOMLDocument [source]
Load a TOML file from a file-like object or path.
Return an empty document if the file doesn’t exist.
Drop-in replacement for
tomlkit.api.load()
.
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, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]
Bases:
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. Run 'nitpick init' or configure a style manually (.nitpick.toml, pyproject.toml). See https://nitpick.rtfd.io/en/latest/configuration.html")
- class nitpick.violations.Reporter(info: FileInfo | None = None, violation_base_code: int = 0)[source]
Bases:
object
Error reporter.
- make_fuss(violation: ViolationEnum, suggestion: str = '', fixed=False, **kwargs) Fuss [source]
Make a fuss.
Bases:
ViolationEnum
Shared violations used by all plugins.
- class nitpick.violations.StyleViolations(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]
Bases:
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}')
- NO_STYLE_CONFIGURED = (4, "No style file configured. Run 'nitpick init' or configure a style manually (.nitpick.toml, pyproject.toml). See https://nitpick.rtfd.io/en/latest/configuration.html")