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 the CONFIG_FILES.

cache: str
doc: TOMLDocument
dont_suggest: Array
file: Path
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.

  1. Get all root keys from the merged style (every key is a filename, except “nitpick”).

  2. 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.

offline: bool
project: Project
run(*partial_names: str, autofix=False) Iterator[Fuss][source]

Run Nitpick.

Parameters:
  • partial_names – Names of the files to enforce configs for.

  • autofix – Flag to modify files, if the plugin supports it (default: True).

Returns:

Fuss generator.

classmethod singleton() Nitpick[source]

Return a single instance of the class.

class nitpick.core.Project(root: PathOrStr | None = None)[source]

Bases: object

A project to be nitpicked.

config_file() Path | None[source]

Determine which config file to use.

config_file_or_default() Path[source]

Return a config file if found, or the default one.

merge_styles(offline: bool) Iterator[Fuss][source]

Merge one or multiple style files.

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.

property root: Path

Root dir of the project.

suggest_styles(library_path_str: PathOrStr | None) list[str][source]

Suggest styles based on the files in the project root (skipping Git ignored files).

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 on pyproject.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 the

    explicitly declared fields. additional and fields are mutually-exclusive options.

  • include: Dictionary of additional fields to include in the schema. It is

    usually 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 index

    of 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 deserialization

  • unknown: Whether to exclude, include, or raise an error for unknown

    fields in the data. Use EXCLUDE, INCLUDE or RAISE.

  • register: Whether to register the Schema with marshmallow’s internal

    class 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'>}
property dict_class: type
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. A ValidationError is raised if obj 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. A ValidationError is raised if obj 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

fields: Dict[str, ma_fields.Field]

Dictionary mapping field_names -> Field objects

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:
  • fields (dict) – Dictionary mapping field names to field instances.

  • name (str) – Optional name for the class, which will appear in the repr for the class.

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 and attr.

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. A ValidationError 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. A ValidationError 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 a node_modules subdir for instance.