---
title: "API reference"
description: "Public classes, modules, constructors, methods, return types, ABC registrations and pickling for strsimpy 0.5.0."
---

> Documentation Index
> Fetch the complete documentation index at: https://luozhouyang.github.io/python-string-similarity/llms.txt
> Use this file to discover all available pages before exploring further.

# API reference

This page is the complete public API index for `strsimpy` 0.5.0. All names are
available from the package root, and the historical per-module imports return
the same objects.

## Conventions

- `s0` and `s1` are Python `str` values. Lengths and indices refer to Unicode
  code points, matching `len(str)` and indexing.
- A **distance** is `0` for identical strings and grows as strings differ. A
  **similarity** is `1` for identical strings. An alignment **score** is a raw
  value and may be negative.
- Method signatures show defaults. `Cosine(k)` and `Jaccard(k)` require `k`;
  the other shingle measures default to `k=3`.
- Return types are Python types. The integral-distance quirk is described in
  [Return types](#return-types).

## Base classes and helper

| Class or helper | Module | Signature | Methods and returns |
| --- | --- | --- | --- |
| `StringDistance` | `strsimpy.string_distance` | abstract base | `distance(s0, s1)` raises `NotImplementedError` |
| `NormalizedStringDistance` | `strsimpy.string_distance` | subclass of `StringDistance` | `distance(s0, s1)` raises `NotImplementedError` |
| `MetricStringDistance` | `strsimpy.string_distance` | subclass of `StringDistance` | `distance(s0, s1)` raises `NotImplementedError` |
| `StringSimilarity` | `strsimpy.string_similarity` | abstract base | `similarity(s0, s1)` raises `NotImplementedError` |
| `NormalizedStringSimilarity` | `strsimpy.string_similarity` | subclass of `StringSimilarity` | `similarity(s0, s1)` raises `NotImplementedError` |
| `ShingleBased` | `strsimpy.shingle_based` | `ShingleBased(k=3)` | `get_k() -> int`; `get_profile(string) -> dict[str, int]` |
| `shingle_profile` | `strsimpy._strsimpy` | `shingle_profile(string, k)` | `dict[str, int]` |

> **Virtual registration**
>
> The native calculators are not Python subclasses of these ABCs. They are
> registered as virtual subclasses, so `isinstance(Levenshtein(), StringDistance)`
> and `issubclass(...)` work as they did in the pure-Python releases. The
> distance and similarity base classes are instantiable, but their methods raise
> `NotImplementedError`.
>
> `ShingleBased` can be used directly: `ShingleBased(2).get_profile("abc")`
> returns `{'ab': 1, 'bc': 1}`, the same result as
> `shingle_profile("abc", 2)`.

## Edit and sequence measures

| Class | Module | Constructor | Methods and returns | Notes |
| --- | --- | --- | --- | --- |
| `Levenshtein` | `strsimpy.levenshtein` | `Levenshtein()` | `distance(s0, s1) -> int`; float `0.0` when equal | Metric distance. Two rolling rows. |
| `NormalizedLevenshtein` | `strsimpy.normalized_levenshtein` | `NormalizedLevenshtein()` | `distance(s0, s1) -> float`; `similarity(s0, s1) -> float` | Distance is the raw distance divided by the longer length; similarity is its complement. The `levenshtein` attribute exposes a `Levenshtein` instance. |
| `WeightedLevenshtein` | `strsimpy.weighted_levenshtein` | `WeightedLevenshtein(substitution_cost_fn=None, insertion_cost_fn=None, deletion_cost_fn=None)` | `distance(s0, s1) -> float` | Insertion and deletion callables receive one character; the substitution callable receives two. Omitted callables use unit costs. The three attributes are readable and writable. |
| `Damerau` | `strsimpy.damerau` | `Damerau()` | `distance(s0, s1) -> int`; float `0.0` when equal | Unrestricted Damerau-Levenshtein with adjacent transpositions; metric. |
| `OptimalStringAlignment` | `strsimpy.optimal_string_alignment` | `OptimalStringAlignment()` | `distance(s0, s1) -> int`; float `0.0` when equal; `alignment(s0, s1) -> list[tuple[str, str, str]]` | Restricted edit distance. Alignment ops are `insert`, `delete`, `substitute` and `transpose`. Not a metric. |
| `JaroWinkler` | `strsimpy.jaro_winkler` | `JaroWinkler(threshold=0.7)` | `similarity(s0, s1) -> float`; `distance(s0, s1) -> float`; `get_threshold() -> float`; static `matches(s0, s1) -> list[int]` | `matches()` returns `[matches, transpositions, prefix, max_len]`. Attributes: `threshold`, `three` (3), `jw_coef` (0.1). |
| `StrCmp95` | `strsimpy.strcmp95` | `StrCmp95(long_strings=False)` | `similarity(s0, s1) -> float`; `distance(s0, s1) -> float` | US Census routine; strips surrounding whitespace and uppercases. Attribute: `long_strings`. |
| `MLIPNS` | `strsimpy.mlipns` | `MLIPNS(threshold=0.25, max_mismatches=2)` | `similarity(s0, s1) -> float`; `distance(s0, s1) -> float` | Binary result: exactly `0.0` or `1.0`. Attributes: `threshold`, `max_mismatches`. Not a metric. |
| `LongestCommonSubsequence` | `strsimpy.longest_common_subsequence` | `LongestCommonSubsequence()` | `distance(s0, s1) -> int`; float `0.0` when equal; static `length(s0, s1) -> int` | Distance is `len(s0) + len(s1) - 2 * LCS length`. |
| `MetricLCS` | `strsimpy.metric_lcs` | `MetricLCS()` | `distance(s0, s1) -> float` | Normalized LCS distance in `[0, 1]`; metric. The `lcs` attribute exposes a `LongestCommonSubsequence` instance. |
| `RatcliffObershelp` | `strsimpy.ratcliff_obershelp` | `RatcliffObershelp()` | `similarity(s0, s1) -> float`; `distance(s0, s1) -> float` | Gestalt pattern matching with `difflib` tie-breaking. Can be asymmetric. |
| `NGram` | `strsimpy.ngram` | `NGram(n=2)` | `distance(s0, s1) -> float` | Kondrak normalized n-gram distance. The `n` attribute is readable and writable; `n=0` raises `ValueError`. No `similarity()`. |

## Shingle and set measures

All classes in this section build a k-shingle profile after collapsing runs of
Python whitespace to one ASCII space. `get_profile()` returns a plain
`dict[str, int]`.

| Class | Module | Constructor | Methods and returns | Notes |
| --- | --- | --- | --- | --- |
| `QGram` | `strsimpy.qgram` | `QGram(k=3)` | `distance(s0, s1) -> int`; float `0.0` when equal; `get_k() -> int`; `get_profile(string) -> dict[str, int]`; static `distance_profile(profile0, profile1) -> int` | L1 distance between profiles. `distance_profile()` accepts any mapping. Not normalized. |
| `Cosine` | `strsimpy.cosine` | `Cosine(k)` | `similarity(s0, s1) -> float`; `distance(s0, s1) -> float`; `get_k() -> int`; `get_profile(string) -> dict[str, int]`; `similarity_profiles(profile0, profile1) -> float` | `k` is required. A zero-norm profile yields similarity `0.0` through `similarity_profiles()`; identical raw strings are still special-cased to `1.0`. `similarity_profiles()` accepts any numeric mapping. |
| `Jaccard` | `strsimpy.jaccard` | `Jaccard(k)` | `similarity(s0, s1) -> float`; `distance(s0, s1) -> float`; `get_k() -> int`; `get_profile(string) -> dict[str, int]` | `k` is required. Set semantics; metric distance. |
| `SorensenDice` | `strsimpy.sorensen_dice` | `SorensenDice(k=3)` | `similarity(s0, s1) -> float`; `distance(s0, s1) -> float`; `get_k() -> int`; `get_profile(string) -> dict[str, int]` | Set semantics; not a metric. |
| `OverlapCoefficient` | `strsimpy.overlap_coefficient` | `OverlapCoefficient(k=3)` | `similarity(s0, s1) -> float`; `distance(s0, s1) -> float`; `get_k() -> int`; `get_profile(string) -> dict[str, int]` | Set semantics; similarity is `1.0` when one set is a subset of the other. |
| `Tversky` | `strsimpy.tversky` | `Tversky(k=3, alpha=1.0, beta=1.0)` | `similarity(s0, s1) -> float`; `distance(s0, s1) -> float`; `get_k() -> int`; `get_profile(string) -> dict[str, int]` | Set semantics. Attributes: `alpha`, `beta`. Asymmetric when `alpha != beta`. |
| `Tanimoto` | `strsimpy.tanimoto` | `Tanimoto(k=3)` | `similarity(s0, s1) -> float`; `distance(s0, s1) -> float`; `get_k() -> int`; `get_profile(string) -> dict[str, int]` | Standard set coefficient; identical to `Jaccard`, and its distance is a metric. |

## Token measures

| Class | Module | Constructor | Methods and returns | Notes |
| --- | --- | --- | --- | --- |
| `Bag` | `strsimpy.bag` | `Bag()` | `distance(s0, s1) -> int` | Character-multiset metric. No `similarity()` and no normalized form. |
| `MongeElkan` | `strsimpy.monge_elkan` | `MongeElkan(symmetric=False, inner="jaro_winkler")` | `similarity(s0, s1) -> float`; `distance(s0, s1) -> float` | Whitespace tokenization. `inner` is `"jaro_winkler"` or `"normalized_levenshtein"`. Attributes: `symmetric`, `inner`. Asymmetric by default. |

## Sequence alignment

| Class | Module | Constructor | Methods and returns | Notes |
| --- | --- | --- | --- | --- |
| `NeedlemanWunsch` | `strsimpy.needleman_wunsch` | `NeedlemanWunsch(match_score=1.0, mismatch_score=-1.0, gap_cost=1.0)` | `score(s0, s1) -> float`; `alignment(s0, s1) -> list[tuple[str, str, str]]` | Global alignment with a linear gap. Attributes mirror the constructor. |
| `SmithWaterman` | `strsimpy.smith_waterman` | `SmithWaterman(match_score=1.0, mismatch_score=-1.0, gap_cost=1.0)` | `score(s0, s1) -> float`; `alignment(s0, s1) -> list[tuple[str, str, str]]` | Local alignment; score is the maximum matrix cell and is non-negative. Attributes mirror the constructor. |
| `Gotoh` | `strsimpy.gotoh` | `Gotoh(match_score=1.0, mismatch_score=-1.0, gap_open=1.0, gap_extend=0.5)` | `score(s0, s1) -> float`; `alignment(s0, s1) -> list[tuple[str, str, str]]` | Global alignment with affine gaps. A gap of length `L` costs `gap_open + (L - 1) * gap_extend`. Attributes mirror the constructor. |

Alignment methods return `(op, source, target)` tuples where `op` is `"match"`,
`"substitute"`, `"insert"` or `"delete"`, and a gap is the empty string on the
missing side. These classes are **not** registered as `StringDistance` or
`StringSimilarity`; they have no normalized distance or similarity.

## Compression

| Class | Module | Constructor | Methods and returns | Notes |
| --- | --- | --- | --- | --- |
| `NormalizedCompressionDistance` | `strsimpy.normalized_compression_distance` | `NormalizedCompressionDistance(compressor="rle")` | `distance(s0, s1) -> float` | Only `"rle"` is available; an unknown compressor raises `ValueError`. Attribute: `compressor`. Not registered as a `StringDistance`. |

## Experimental

| Class | Module | Constructor | Methods and returns | Notes |
| --- | --- | --- | --- | --- |
| `SIFT4` | `strsimpy.sift4` | `SIFT4()` | `distance(s1, s2, maxoffset=5, options=None) -> int` | Heuristic distance. `options` must be a dictionary, not a `SIFT4Options` instance. The binding returns an `int`. Not registered as a `StringDistance`. |
| `SIFT4Options` | `strsimpy.sift4` | `SIFT4Options(options=None)` | `options -> dict`; `maxdistance -> int`; tokenizer and evaluator attributes; static tokenizer and evaluator helpers; `distance(s0, s1)` raises `NotImplementedError` | Validates an options dictionary and exposes the resolved settings. Registered as `StringDistance` and `MetricStringDistance` for compatibility only. |

`SIFT4Options` static helpers include `ngramtokenizer(s, n=2)`,
`wordsplittokenizer(s)`, `characterfrequencytokenizer(s)`,
`sift4matchingevaluator(token1, token2)`, `rewardlengthevaluator(length)`,
`rewardlengthevaluator2(length)` and
`longertranspositionsaremorecostly(c1, c2)`. The `distance()` method exists
only because the class is registered in the base-class compatibility layer; it
always raises `NotImplementedError`.

## ABC registration

`SD` is `StringDistance`, `NSD` is `NormalizedStringDistance`, `MSD` is
`MetricStringDistance`, `SS` is `StringSimilarity`, `NSS` is
`NormalizedStringSimilarity`, and `SB` is `ShingleBased`. A dash means the
class is not registered for that ABC.

| Class | SD | NSD | MSD | SS | NSS | SB |
| --- | --- | --- | --- | --- | --- | --- |
| `Levenshtein` | yes | - | yes | - | - | - |
| `NormalizedLevenshtein` | yes | yes | - | yes | yes | - |
| `WeightedLevenshtein` | yes | - | - | - | - | - |
| `Damerau` | yes | - | yes | - | - | - |
| `OptimalStringAlignment` | yes | - | - | - | - | - |
| `JaroWinkler` | yes | yes | - | yes | yes | - |
| `StrCmp95` | yes | yes | - | yes | yes | - |
| `MLIPNS` | yes | yes | - | yes | yes | - |
| `LongestCommonSubsequence` | yes | - | - | - | - | - |
| `MetricLCS` | yes | yes | yes | - | - | - |
| `RatcliffObershelp` | yes | yes | - | yes | yes | - |
| `NGram` | yes | yes | - | - | - | - |
| `QGram` | yes | - | - | - | - | yes |
| `Cosine` | yes | yes | - | yes | yes | yes |
| `Jaccard` | yes | yes | yes | yes | yes | yes |
| `SorensenDice` | yes | yes | - | yes | yes | yes |
| `OverlapCoefficient` | yes | yes | - | yes | yes | yes |
| `Tversky` | yes | yes | - | yes | yes | yes |
| `Tanimoto` | yes | yes | yes | yes | yes | yes |
| `Bag` | yes | - | yes | - | - | - |
| `MongeElkan` | yes | yes | - | yes | yes | - |
| `NeedlemanWunsch` | - | - | - | - | - | - |
| `SmithWaterman` | - | - | - | - | - | - |
| `Gotoh` | - | - | - | - | - | - |
| `NormalizedCompressionDistance` | - | - | - | - | - | - |
| `SIFT4` | - | - | - | - | - | - |
| `SIFT4Options` | yes | - | yes | - | - | - |

Every `NSD` registration also satisfies `SD`, and every `MSD` registration also
satisfies `SD`, because both ABCs subclass `StringDistance`. Likewise, every
`NSS` registration also satisfies `SS`, because `NormalizedStringSimilarity`
subclasses `StringSimilarity`.

## Pickling

Every public calculator supports pickle round-trips, including the alignment
classes, `NormalizedCompressionDistance`, `SIFT4` and `SIFT4Options`.
Constructor options are preserved:

| Class | Preserved state |
| --- | --- |
| `JaroWinkler` | `threshold` |
| `NGram` | `n` |
| `QGram`, `Cosine`, `Jaccard`, `SorensenDice`, `OverlapCoefficient`, `Tanimoto` | shingle size `k` |
| `Tversky` | `k`, `alpha`, `beta` |
| `MLIPNS` | `threshold`, `max_mismatches` |
| `StrCmp95` | `long_strings` |
| `MongeElkan` | `symmetric`, `inner` |
| `WeightedLevenshtein` | the three cost callables, if they are picklable |
| `NeedlemanWunsch`, `SmithWaterman`, `Gotoh` | score and gap parameters |
| `NormalizedCompressionDistance` | `compressor` |
| `SIFT4Options` | the resolved options dictionary |

Bound methods are picklable, so a bound `distance` method can be sent to a
multiprocessing worker. A `WeightedLevenshtein` cost function must itself be
picklable; use a top-level function rather than a lambda.

```python
import pickle

from strsimpy import JaroWinkler, Levenshtein

restored = pickle.loads(pickle.dumps(JaroWinkler(0.5)))
print(restored.get_threshold())

distance = pickle.loads(pickle.dumps(Levenshtein().distance))
print(distance("abc", "adc"))
```

```text
0.5
1
```

## Return types

Most normalized measures return `float`. The following patterns are deliberate
and match the historical pure-Python API:

- `Levenshtein`, `Damerau`, `OptimalStringAlignment`,
  `LongestCommonSubsequence` and `QGram` return a Python `int` for unequal
  inputs, but the float `0.0` when the inputs are identical.
- `Bag` always returns an `int`.
- `SIFT4.distance()` always returns an `int`; the native binding casts the
  computed value.
- `MLIPNS.similarity()` and `MLIPNS.distance()` return exactly `0.0` or `1.0`.
- `WeightedLevenshtein` and all normalized distances and similarities return
  `float`.
- `JaroWinkler.matches()` returns a list of four `int` values.
- `alignment()` returns a list of `(op, source, target)` string triples.
  Smith-Waterman returns an empty list when no positive-scoring local alignment
  exists.
- `get_profile()` returns a `dict` mapping shingle strings to `int` counts.
- `shingle_profile()` returns the same dictionary shape.

## Constructor validation

| Constructor | Validation |
| --- | --- |
| `NGram(n=2)` | `n` must be greater than 0; `n=0` raises `ValueError`. The `n` setter applies the same check. |
| `Tversky(k=3, alpha=1.0, beta=1.0)` | `alpha` and `beta` must be finite, non-negative, and not both zero. |
| `MLIPNS(threshold=0.25, max_mismatches=2)` | `threshold` must be finite and between 0 and 1. |
| `NeedlemanWunsch`, `SmithWaterman`, `Gotoh` | Scores must be finite; gap parameters must be finite and non-negative. |
| `MongeElkan(symmetric=False, inner="jaro_winkler")` | `inner` must be `"jaro_winkler"` or `"normalized_levenshtein"`. |
| `NormalizedCompressionDistance(compressor="rle")` | Only `"rle"` is accepted. |
| `SIFT4Options(options=None)` | `options` must be a dictionary; unknown keys, preset names and a non-integer `maxdistance` raise `ValueError`. |
| `Cosine(k)`, `Jaccard(k)` | `k` is required; there is no default in 0.5.0. Other shingle classes default to `k=3`. |

## Version and support

- `strsimpy.__version__` reports `0.5.0`.
- Supported Python versions are 3.10 and newer. Prebuilt abi3 wheels cover
  Linux, macOS and Windows; building from source requires Rust 1.85 or newer
  and `maturin`.
- See the [changelog](https://luozhouyang.github.io/python-string-similarity/reference/changelog/) for release highlights and the
  [guides](https://luozhouyang.github.io/python-string-similarity/guides/choosing-an-algorithm/) for task-based selection advice.

Source: https://luozhouyang.github.io/python-string-similarity/reference/api/index.mdx
