Skip to content

API reference

Everything below is exported from ecfr_md.

Code of Federal Regulations text from the eCFR API, as navigable Markdown.

The public API is what this module exports, plus the response models in :mod:ecfr_md.models. Other modules are internal and may change.

import ecfr_md section = ecfr_md.get("45 CFR 164.502") ecfr_md.save("45 CFR Part 164", "hipaa.md")

The module-level functions share one client, with settings from the config file and ECFR_MD_* variables; ecfr_md.configure(...) changes them. For a client of your own, or to close connections when done, use :class:ECFR:

from ecfr_md import ECFR, Settings with ECFR(Settings(user_agent="my-app/1.0")) as ecfr: ... part = ecfr.get("45 CFR Part 164")

LevelName module-attribute

LevelName = Literal[
    "title",
    "subtitle",
    "chapter",
    "subchapter",
    "part",
    "subpart",
    "subject_group",
    "section",
    "appendix",
    "paragraph",
]

The name of a :class:Level, for type checkers.

Format module-attribute

Format = Literal[
    "markdown",
    "text",
    "html",
    "json",
    "epub",
    "docx",
    "pdf",
]

An export format's name.

Address dataclass

Address(
    title: int,
    hierarchy: Hierarchy = Hierarchy(),
    paragraph: tuple[str, ...] = (),
    group: str | None = None,
    date: date | None = None,
)

A place in the CFR, down to a paragraph, optionally at a date.

str(Address.parse("45 CFR 164.502(a)(1)")) '45/164.502/a/1' Address.parse("45/part-164/subpart-E").citation() '45 CFR Part 164 Subpart E'

hierarchy holds the levels, as for the API; an appendix may be its key ("appendix-A") or full name. paragraph holds the markers, where a marker repeated among its siblings has its occurrence ("1~2"). group is a subject group's eCFR id; date is None for the latest.

level property

level: str

The level named: "title", "part", "section", "paragraph", ...

markers property

markers: tuple[str, ...]

Paragraph markers without occurrences: ("a", "1").

parse classmethod

parse(
    text: str | int | Address, *, title: int | None = None
) -> Self

Read one place in the CFR, written any common way.

Accepts addresses (45/164.502/a/1@2020-01-01, title-45/..., section-164.502), file names and paths ecfr-md saved, old or new (45_164.502_a_1.md, .../part-164/subpart-E/164.502.md), cfr: URIs, eCFR, LII and GovInfo URLs, USLM identifiers (/us/cfr/t45/s164.502/a/1), GovInfo granule ids and citations as :meth:Citation.parse <ecfr_md.citation.Citation.parse> reads them, plus Bluebook forms (45 C.F.R. § 164.502(a)(1) (2018), where the year means that title's annual edition), spaced markers (164.502 a 1 i) and dotted ones (164.502.a.1).

title is the title for addresses that leave it out, such as 164.502/a. Raises :class:InvalidCitationError, saying what to do, for anything else, and for lists and ranges, which :meth:parse_many reads.

parse_many classmethod

parse_many(
    text: str | int, *, title: int | None = None
) -> list[Self]

Read one or several places: a list such as 45/164.502,164.504 or 45 CFR §§ 164.502, 164.506, or a range of paragraphs such as 45/164.502/b..d. Accepts everything :meth:parse does.

citation

citation(
    style: Literal["ofr", "bluebook"] = "ofr",
    year: int | None = None,
) -> str

A citation: "ofr" as the Federal Register writes them (45 CFR 164.502(a)(1)), or "bluebook" (45 C.F.R. § 164.502(a)(1) (2024)), with year or else the year of the address's date, if any.

to_citation

to_citation() -> Citation

The citation's levels and markers, without occurrences or date.

url

url(site: str = SITE_URL) -> str

The eCFR web page (on site), as the eCFR links it: sections by number (/current/title-45/section-164.502#p-164.502(a)(1)), everything else under its part (.../part-1026/appendix-Supplement%20I%20to...).

uri

uri() -> str

The address as a URI, e.g. cfr:45/164.502/a/1@2024-01-01.

file_name

file_name() -> str

A file name for the text at this address, e.g. "45_164.502_a_1.md", or with a date "45_164.502_a_1@2020-01-01.md".

undated

undated() -> Address

The same place without a date.

Citation dataclass

Citation(
    title: int,
    hierarchy: Hierarchy = Hierarchy(),
    paragraph: tuple[str, ...] = (),
)

A location in the CFR, down to a paragraph.

Citation.parse("45 CFR 164.502(a)(1)") Citation(title=45, hierarchy={'section': '164.502'}, paragraph=('a', '1'))

parse classmethod

parse(text: str | int) -> Self

Parse a citation.

Understands, case-insensitively and with or without §, commas and dots in "C.F.R.": 45, Title 45, 45 CFR 164, 45 CFR Part 164 Subpart E, 45 CFR 164.502(a)(1)(i)(A), 45 CFR Subtitle A Chapter I Subchapter C, 45 CFR Appendix A to Subpart C of Part 164 and other appendix-level names such as 12 CFR Supplement I to Part 1026.

Citations can be pasted as found: surrounding quotes and invisible characters are dropped, Supp. and app. are completed from the part (12 CFR pt. 1026, app. J is Appendix J to Part 1026), a trailing et seq. is ignored (the citation is its first section), and Subpart E of Part 164 and Part 164 of Title 45 work.

Raises :class:InvalidCitationError, saying what to do instead, for a range or list of sections (:meth:parse_many expands lists), a trailing year such as (2023) (:class:~ecfr_md.address.Address reads it as that year's annual edition), CRF for CFR and unbalanced parentheses.

parse_many classmethod

parse_many(text: str | int) -> list[Self]

Parse a citation that may list several sections.

45 CFR §§ 164.502, 164.506 and 45 CFR 164.502 and 164.506(a) give one citation per section, all in the same title. Ranges such as 164.500-164.534 are not expanded, since only the eCFR knows which sections lie between the ends: they raise :class:InvalidCitationError as in :meth:parse. Anything else is parsed as one citation.

with_hierarchy

with_hierarchy(hierarchy: Mapping[str, object]) -> Self

Add hierarchy levels, rejecting any that contradict existing ones.

with_section

with_section(text: str) -> Self

Add a section number and any trailing paragraph markers.

The part isn't inferred from the number: in some parts sections are numbered differently (43 CFR Part 4100 holds § 4110.1).

with_appendix

with_appendix(name: str) -> Self

Add a full appendix name, plus its part if the name ends in one.

ECFR

ECFR(
    settings: Settings | None = None,
    *,
    transport: BaseTransport | None = None,
    progress: Progress | None = None,
)

eCFR API client.

Use as a context manager so connections are released::

with ECFR() as ecfr:
    part = ecfr.get("45 CFR Part 164")

get

get(
    citation: str | int,
    /,
    *,
    date: DateLike | None = None,
    **hierarchy: Unpack[Hierarchy],
) -> Node

Fetch regulation text as a navigable :class:~ecfr_md.document.Node.

One request returns the whole node; navigating it makes no more.

Parameters

citation: str | int A title number, citation or address: 45, "45 CFR 164", "45 CFR Part 164 Subpart E", "45 CFR 164.502(a)(1)(i)(A)", "45/164.502/a/1", an eCFR link, a saved file's name, or anything else :meth:Address.parse <ecfr_md.address.Address.parse> reads. Hierarchy keywords (part="164", ...) refine it. date: DateLike | None Point-in-time date: a date, datetime or text such as "2020-01-01", "Jan 1 2020" or "last year". Defaults to the date in the citation (@2020-01-01, or a Bluebook year's edition), else the most recent available. **hierarchy: Hierarchy Levels that refine the citation: subtitle, chapter, subchapter, part, subpart, section or appendix, e.g. part="164".

titles

titles() -> list[TitleInfo]

Every CFR title: number, name, latest date, and whether reserved.

Uses the title list the client keeps for a few minutes, so it is usually free.

outline

outline(
    citation: str | int | None = None,
    /,
    *,
    date: DateLike | None = None,
    **hierarchy: Unpack[Hierarchy],
) -> Outline

The table of contents of a title or any part of it, without its text.

Index it like a node (outline["Subpart E"]) or print it. Uses the structure endpoint, which is much smaller than the text and is kept in the cache. Move with .next, .previous, .up and .siblings, and fetch the text with .read().

Parameters

citation: str | int | None A title number, citation or address, as for :meth:get. Leave it out for the whole CFR: one entry per title, each title's structure loaded the first time it's opened. date: DateLike | None Point-in-time date. Defaults to the date in the citation, else the most recent available. **hierarchy: Hierarchy Levels that refine the citation: subtitle, chapter, subchapter, part, subpart, section or appendix, e.g. part="164".

compare

compare(
    citation: str | int,
    /,
    since: DateLike,
    until: DateLike | None = None,
    **hierarchy: Unpack[Hierarchy],
) -> Comparison

What changed in the text between two dates, block by block.

Each changed paragraph (or table, or note) is a :class:~ecfr_md.compare.Difference that can show its words deleted and inserted; to_markdown() gives a redline of them all.

Parameters

citation: str | int A title number or citation, as for :meth:get. since: DateLike The earlier date, e.g. the day before a change took effect. until: DateLike | None The later date. Defaults to the most recent available. **hierarchy: Hierarchy Levels that refine the citation: subtitle, chapter, subchapter, part, subpart, section or appendix, e.g. part="164".

changes

changes(
    citation: str | int,
    /,
    *,
    since: DateLike | None = None,
    until: DateLike | None = None,
    **hierarchy: Unpack[Hierarchy],
) -> list[Change]

Changes the eCFR has issued to a title or any part of it, newest first.

Each change is a version of a section or appendix: its citation, when the eCFR issued it, when it took effect (effective), and its kind: "substantive", "editorial" or "removed". Uses the versions endpoint; no text is downloaded.

Parameters

citation: str | int A title number, citation or address, as for :meth:get. since: DateLike | None Only changes issued on or after this date. until: DateLike | None Only changes issued on or before this date. **hierarchy: Hierarchy Levels that refine the citation: subtitle, chapter, subchapter, part, subpart, section or appendix, e.g. part="164".

search

search(
    query: str,
    /,
    *,
    limit: Annotated[int, Field(ge=1)] = 20,
    phrase: bool | None = None,
    all_versions: bool = False,
    **filters: Unpack[SearchFilters],
) -> Matches

Sections and appendices that match a search, best first.

Each match has a citation to pass to :meth:get, a heading and an excerpt; matches.total is how many the eCFR found, and matches.note says when the search was widened.

Plain words find the exact phrase first, then sections with all the words in any form ("ethnic slur" also finds "ethnic slurs"). The eCFR's operators work too: "exact phrase", -exclude, a | b, ( ), prefix* and "phrase"~3, and AND, OR, NOT in capitals (see :mod:ecfr_md.query). A quoted phrase that matches nothing is searched again as words.

Parameters

query: str Words or a query to search headings and text for. limit: int Maximum number of matches to return. phrase: bool | None For plain words: True finds only the exact phrase, False only all the words; by default, the phrase first, then the words. Ignored for queries with operators. all_versions: bool Include past versions of sections, not only current text. **filters: SearchFilters within (a citation such as "45 CFR Part 164"), agency_slugs, date and the last_modified_* dates.

define

define(
    term: str,
    citation: str | int,
    /,
    *,
    date: DateLike | None = None,
) -> Definitions

The definitions of a term that govern a place in the CFR.

Looks in the place's own text (for a section), then in the definitions sections of each division it's in, nearest first, and keeps the definitions that apply to it: for 45 CFR 164.502, "covered entity" is defined in 45 CFR 160.103, whose definitions apply to the whole subchapter. Each :class:Definition <ecfr_md.definitions.Definition> has the text, its pinpoint citation and what it applies to. If none is found, suggestions has similar terms that are defined, and mentions sections that may define it, found by search.

Parameters

term: str The term, e.g. "covered entity"; case and plurals don't matter. citation: str | int Where the term is used: a section, part or other division. date: DateLike | None Point-in-time date. Defaults to the most recent available.

verify_quote

verify_quote(
    citation: str | int,
    /,
    text: str,
    *,
    date: DateLike | None = None,
) -> QuoteCheck

Check that text is in the text of citation, word for word.

Formatting, whitespace, curly quotes, dashes and paragraph labels don't count. If it isn't there, the result has the nearest passage and how alike they are; if it's somewhere else in the text fetched (another paragraph or section of the part), it is found but not at the citation (verified is false either way).

Parameters

citation: str | int The pinpoint the quote is attributed to, e.g. 45 CFR 164.502(a)(1). text: str The quoted words. date: DateLike | None Point-in-time date. Defaults to the most recent available.

cited_by

cited_by(
    citation: str | int,
    /,
    *,
    limit: Annotated[int, Field(ge=1)] = 20,
    date: DateLike | None = None,
) -> Matches

Sections and appendices that may cite a section or part.

Approximate: this searches the eCFR for the section number (or "part N"), so it finds citations written that way, in the same title or naming the title ("45 CFR 164.502"), but not "paragraph (a) of this section" and the like. A paragraph counts as its section.

Parameters

citation: str | int A section or part (or anything in one), as for :meth:get. limit: int Maximum number of matches to return. date: DateLike | None Only text in effect on this date. Defaults to the current text.

definitions

definitions(
    citation: str | int, /, *, date: DateLike | None = None
) -> list[Definition]

Every defined term that governs a place, nearest first.

Reads the same definitions sections as :meth:define, keeping those that apply to the place; where a term is defined at several levels, the nearest definition wins.

Parameters

citation: str | int Where the terms are used: a section, part or other division. date: DateLike | None Point-in-time date. Defaults to the most recent available.

sync

sync(
    path: str | Path,
    *,
    dry_run: bool = False,
    include_dated: bool = False,
    force: bool = False,
    migrate: bool = False,
) -> SyncResult

Update Markdown saved by ecfr-md to the latest eCFR text.

path is a saved file, a saved tree, or a directory of them, searched to any depth. Only files whose text changed are rewritten; files for sections that no longer exist are deleted. See :mod:ecfr_md.syncing.

Parameters

dry_run: bool Report what would change without writing anything. include_dated: bool Also move snapshots saved with a past date to the latest text; by default they are kept (SyncResult.kept). force: bool Also overwrite or delete files edited since they were saved; by default they are left alone (SyncResult.modified). migrate: bool Rename files and folders saved by ecfr-md 0.x to today's layout (SyncResult.moved); by default they keep their names.

get_many

get_many(
    citations: Sequence[str | int],
    *,
    date: DateLike | None = None,
    errors: Literal["raise"] = "raise",
) -> list[Node]
get_many(
    citations: Sequence[str | int],
    *,
    date: DateLike | None = None,
    errors: Literal["return"],
) -> list[Node | ECFRError]
get_many(
    citations: Sequence[str | int],
    *,
    date: DateLike | None = None,
    errors: Literal["raise", "return"] = "raise",
) -> list[Node] | list[Node | ECFRError]

Fetch several citations, sharing requests where possible.

Sections in the same small part (up to GROUP_BELOW bytes) are fetched with one request for the part. Results are in input order.

Parameters

citations: Sequence[str | int] Citations, as for :meth:get. date: DateLike | None Point-in-time date for all of them. Defaults to the most recent. errors: "raise" | "return" With "return", a citation that fails gives its exception in its place in the list, and the others are still fetched.

save

save(
    citation: str | int,
    /,
    path: str | Path,
    *,
    tree: Literal[False] = False,
    front_matter: bool = True,
    date: DateLike | None = None,
    format: Format | None = None,
    links: bool | None = None,
    **hierarchy: Unpack[Hierarchy],
) -> Path
save(
    citation: str | int,
    /,
    path: str | Path,
    *,
    tree: Literal[True],
    front_matter: bool = True,
    date: DateLike | None = None,
    format: Format | None = None,
    links: bool | None = None,
    **hierarchy: Unpack[Hierarchy],
) -> list[Path]
save(
    citation: str | int,
    /,
    path: str | Path,
    *,
    tree: bool = False,
    front_matter: bool = True,
    date: DateLike | None = None,
    format: Format | None = None,
    links: bool | None = None,
    **hierarchy: Unpack[Hierarchy],
) -> Path | list[Path]

Save regulation text as Markdown, or as text, HTML, JSON, EPUB, Word or PDF.

Returns the file written, or with tree=True the list of files.

Same output as get(...).save(...), but the XML is processed while it is read from disk instead of being loaded whole.

Parameters

citation: str | int A title number or citation, as for :meth:get. path: str | Path Output file, or directory when tree is true. tree: bool Write nested directories, one file per section or appendix. front_matter: bool Start each file with YAML metadata: citation, date, source URL, retrieval time and a note that the eCFR is not an official edition. date: DateLike | None Point-in-time date. Defaults to the date in the citation, else the most recent available. format: Format | None "markdown", "text", "html", "json", "epub", "docx" or "pdf". Defaults to the file's suffix (hipaa.pdf), or Markdown. In a tree, text and HTML get a file per section like Markdown, and the others a file per part. Word and PDF need the docx and pdf extras. links: bool | None Make cross-references links: in a tree, relative links to the files that hold them, and links to the eCFR for anything outside it. Defaults to on for trees, off for single files. **hierarchy: Hierarchy Levels that refine the citation: subtitle, chapter, subchapter, part, subpart, section or appendix, e.g. part="164".

Comparison dataclass

Comparison(
    citation: str,
    since: date,
    until: date,
    differences: list[Difference] = list(),
    unchanged: int = 0,
)

The differences in one citation's text between two dates.

unchanged class-attribute instance-attribute

unchanged: int = 0

Blocks that are the same on both dates.

to_markdown

to_markdown() -> str

A redline: each changed block, with what was deleted and inserted.

to_dict

to_dict() -> dict[str, Any]

JSON-ready: dates, counts and every difference with its words.

Difference dataclass

Difference(
    kind: Literal[
        "added", "removed", "changed", "unchanged"
    ],
    before: str,
    after: str,
)

One block added, removed or changed.

kind instance-attribute

kind: Literal['added', 'removed', 'changed', 'unchanged']

What happened to the block; "unchanged" only from :func:aligned.

before instance-attribute

before: str

The block's Markdown before; empty if added.

after instance-attribute

after: str

The block's Markdown after; empty if removed.

words property

words: list[tuple[Literal['=', '-', '+'], str]]

The change word by word: kept ("="), deleted ("-"), inserted ("+").

to_markdown

to_markdown() -> str

The block with deletions in and insertions in .

Settings

Bases: BaseModel

Settings for the eCFR client: where text comes from and how it's fetched.

Settings() is the defaults plus what you pass. Settings.load() also reads ECFR_MD_* environment variables and the config file, as the command line does.

images property

images: str

Where images in the text are: image_url, else site_url.

links: dict[str, str]

Link templates for other codes, as find_references takes them.

config_file property

config_file: Path

The config file these settings were loaded from, or would be.

load classmethod

load(
    config: str | Path | None = None,
    *,
    env: Mapping[str, str] | None = None,
    origin: Origin = "SDK",
    read: bool = True,
    **overrides: Any,
) -> Self

Settings from the config file and environment, then overrides.

config is the config file; by default ECFR_MD_CONFIG or :func:config_path. A missing file is no error. env defaults to os.environ; origin names where overrides came from in :meth:explain. read=False skips the file and the environment, but still records which file is the config file.

explain

explain() -> dict[str, tuple[Any, Origin]]

Each setting's value and where it came from: "SDK", "CLI", "env ECFR_MD_...", "file " or "default".

Definition dataclass

Definition(
    term: str,
    terms: tuple[str, ...],
    text: str,
    citation: str,
    address: str,
    url: str,
    date: date | None,
    section: str,
    applies_to: str | None,
)

A term's definition: its text, pinpoint citation and what it applies to.

term instance-attribute

term: str

The term as the text writes it, e.g. "Covered entity".

terms instance-attribute

terms: tuple[str, ...]

Every term the definition defines ("Billing cycle", "cycle").

text instance-attribute

text: str

The definition, as Markdown.

citation instance-attribute

citation: str

Where it is: its paragraph, e.g. "12 CFR 1026.2(a)(4)", or for definitions without paragraph labels, the section ("45 CFR 160.103").

section instance-attribute

section: str

The definitions section, e.g. "45 CFR 160.103".

applies_to instance-attribute

applies_to: str | None

The citation of what the definitions section says it applies to, e.g. "45 CFR Chapter A Subchapter C"; None if it doesn't say.

cite

cite() -> str

E.g. '45 CFR 160.103 (definition of "covered entity")'.

Definitions

Definitions(
    definitions: Iterable[Definition] = (),
    *,
    term: str = "",
    scope: str = "",
    searched: list[str] | None = None,
    suggestions: list[str] | None = None,
    mentions: Matches | None = None,
)

Bases: list[Definition]

The definitions of a term that govern a place, nearest first.

searched lists the sections read; suggestions are terms they define that are like the one asked for; mentions are sections the eCFR finds with the term and "means" when no definition was found.

Appendix

Appendix(
    element: Element, parent: Node | None, source: Source
)

Bases: Division

An appendix to a part or subpart; its identifier is its full name.

Chapter

Chapter(
    element: Element, parent: Node | None, source: Source
)

Bases: Division

A chapter, usually one agency's rules, e.g. 45 CFR Chapter I.

Division

Division(
    element: Element, parent: Node | None, source: Source
)

Bases: Node

A level above paragraphs (title to section), backed by an XML DIV.

In a division above the part from a large download, each part's XML is read from disk when it's needed, and only the most recent are kept.

element property

element: Element

The XML DIV of this division.

Level

Bases: StrEnum

A level of the CFR hierarchy, from title down to paragraph.

Members are strings, so node.level == "section" works. Methods that take a level accept its name in any case: "section", "Section".

Node

Node(identifier: str, parent: Node | None, source: Source)

Bases: ABC

A piece of the CFR: iterable over its children, indexable by identifier.

text and to_markdown() are everything inside the node; toc() lists what's inside without the text; to_dict() is a JSON-ready dict.

heading abstractmethod property

heading: str

The node's heading as plain text, e.g. "§ 164.502 Uses and ...".

children abstractmethod property

children: tuple[Node, ...]

Child nodes in document order.

text property

text: str

Everything inside this node as Markdown, the same as to_markdown().

A paragraph's text includes its subparagraphs; its own lead text is :attr:Paragraph.own_text.

url property

url: str

The eCFR web page showing this node, at its date.

section property

section: Node | None

The section this node is in, or itself if it is one.

anchor property

anchor: str | None

The id the eCFR gives this node on its pages, for deep links and HTML anchors: "p-164.502(a)(1)" for a paragraph, "164.502" for a section, "subpart-E", "part-164", "Appendix-A-to-Part-164"; None for other levels. eCFR ids of paragraphs under defined terms include the term, which the text doesn't mark, so those can differ.

references property

references: list[Reference]

Cross-references in :attr:text: "§ 164.501", "paragraph (a)(1) of this section", "42 U.S.C. 1320d", ... with what each points to. See :func:~ecfr_md.references.find_references.

outline property

outline: Outline

This node's entry in the outline of the whole CFR (a paragraph's section). Needs a node from a client, as do next, previous and up.

next property

next: Node | None

The text of the next section or appendix, crossing into the next part or title; None at the end of the CFR. From the text already loaded when it holds it, so stepping through a part costs nothing.

previous property

previous: Node | None

The text of the section or appendix before this node.

up property

up: Node | None

The node this one is in: its parent, or above the text loaded, the division that holds it (fetched); None for a title.

provenance property

provenance: dict[str, Any]

Citation, address, date, eCFR page, API request, retrieval time and generator: the front matter of saved files.

slug abstractmethod property

slug: str

The node's name in a saved tree: "part-164", "164.502" (its file is "164.502.md"), "supplement-I"; a paragraph's marker, "a".

date property

date: date | None

Point-in-time date of the text.

cfr_title property

cfr_title: int

The CFR title number, e.g. 45.

ancestors property

ancestors: tuple[Node, ...]

Parent, grandparent, ... up to the root of the response.

hierarchy property

hierarchy: Hierarchy

API hierarchy parameters that locate this node.

citation property

citation: str

Standard citation, e.g. 45 CFR 164.502(a)(1).

address property

address: str

The node's address, without a date: 45/164.502/a/1, 45/part-164/subpart-E. See :class:~ecfr_md.address.Address.

uri property

uri: str

The address at the node's date: cfr:45/164.502/a/1@2024-01-01.

to_markdown

to_markdown(
    max_chars: int | None = None, *, links: bool = False
) -> str

This node and everything inside it as one Markdown document.

With max_chars, the text is cut at a paragraph boundary to fit, and ends with a note of how many characters were left out. With links, cross-references (see :attr:references) link to the eCFR.

toc

toc(depth: int | None = None) -> str

A table of contents: this node and those inside it, without text.

One line per node, its citation and heading, indented by depth, down to paragraphs. depth limits how many levels below this node are listed; depth=0 is this node alone.

to_dict

to_dict(
    *,
    depth: int | None = None,
    text: bool = True,
    include_raw: bool = False,
) -> dict[str, Any]

This node as a dict ready for json.dumps.

Keys: citation, address, uri, level, identifier, heading, date (ISO format, or None), url (the eCFR page), text (the full Markdown, as :attr:text) and children (dicts like this one).

Parameters

depth: int | None Levels of children to include; 0 leaves out children. Defaults to all of them, down to paragraphs. text: bool Include text. A node's text includes its children's, so for a deep tree consider text=False or a small depth. include_raw: bool Include raw: the node's XML from the API (None for paragraphs, which the XML doesn't delimit).

to_markdown_tree

to_markdown_tree() -> dict[PurePosixPath, str]

Markdown files keyed by relative path, one per section or appendix.

save

save(
    path: str | Path,
    *,
    tree: Literal[False] = False,
    front_matter: bool = True,
    format: Format | None = None,
    links: bool | None = None,
) -> Path
save(
    path: str | Path,
    *,
    tree: Literal[True],
    front_matter: bool = True,
    format: Format | None = None,
    links: bool | None = None,
) -> list[Path]
save(
    path: str | Path,
    *,
    tree: bool = False,
    front_matter: bool = True,
    format: Format | None = None,
    links: bool | None = None,
) -> Path | list[Path]

Write this node to path: Markdown, or another format.

Returns the file written, or with tree=True the list of files. By default this writes one file; an existing directory receives a file named after the address, e.g. 45_164.502.md. With tree=True, path is a directory that gets one folder per hierarchy level and one file per section or appendix. Each Markdown file starts with YAML front matter (see :attr:provenance) unless front_matter is false. Files are replaced atomically.

format is "markdown", "text", "html", "json", "epub", "docx" or "pdf"; by default the file's suffix decides (hipaa.pdf), and Markdown is the default for directories and names without one. See :meth:export.

With links (the default for Markdown trees), cross-references become links: in a tree, relative links to the files that hold them; to the eCFR for anything else.

export

export(
    path: str | Path,
    format: Format | None = None,
    *,
    tree: Literal[False] = False,
    front_matter: bool = True,
) -> Path
export(
    path: str | Path,
    format: Format | None = None,
    *,
    tree: Literal[True],
    front_matter: bool = True,
) -> list[Path]
export(
    path: str | Path,
    format: Format | None = None,
    *,
    tree: bool = False,
    front_matter: bool = True,
) -> Path | list[Path]

Save this node as Markdown, text, HTML, JSON, EPUB, Word or PDF.

The format is format, or else the file's suffix: .md, .txt, .html, .json, .epub, .docx or .pdf. Word and PDF need the docx and pdf extras. With tree, path is a directory: text and HTML get a file per section or appendix and an index page per level, like Markdown; JSON, EPUB, Word and PDF get a file per part.

part.export("hipaa.pdf") part.export("site/", format="html", tree=True)

cite

cite(
    style: Literal["ofr", "bluebook"] = "ofr",
    year: int | None = None,
) -> str

A citation: "ofr" (:attr:citation, 45 CFR 164.502(a)(1)) or "bluebook" (45 C.F.R. § 164.502(a)(1) (2024)), with year or else the year of the node's date.

__getitem__

__getitem__(key: str | int | Address) -> Node

A child by index, or the nearest descendant by identifier.

Keys can be identifiers ("E", "164.502"), name their level ("Subpart E", "§ 164.502"), be full citations ("45 CFR Part 164 Subpart E", "164.502(a)(1)") or paragraph markers (section["(a)(1)"]), or be addresses, relative to the node or not: part["subpart-E"], part["164.512/k/1"], section["a/1"], section["1~2"] (the second (1)), node["45/164.502"] or an :class:Address. Raises NodeNotFoundError if nothing matches and AmbiguousNodeError if several nodes match at the nearest depth.

get

get(
    key: str | int | Address, default: Node | None = None
) -> Node | None

Like node[key], but return default when nothing matches.

Ambiguous keys still raise AmbiguousNodeError.

iter

iter(
    level: Level | LevelName | None = None,
) -> Iterator[Node]

Every descendant in document order, optionally only one level.

part.iter("section") yields all sections at any depth. Level names are case-insensitive; an unknown one raises InvalidParameterError.

find

find(
    identifier: str | None = None,
    *,
    level: Level | LevelName | None = None,
) -> Node | None

The first descendant (nearest, then in document order) that matches.

Unlike node[...], this doesn't check that the match is unique. Returns None if nothing matches.

Paragraph

Paragraph(marker: str, depth: int, parent: Node)

Bases: Node

A numbered paragraph of a section, e.g. 45 CFR 164.502(a)(1).

Levels nest as (a), (1), (i), (A), then italic (1) and (i); depth is 1 to 6. text includes subparagraphs; own_text doesn't.

path property

path: tuple[str, ...]

Markers from the section down, e.g. ('a', '1', 'i').

markers property

markers: tuple[str, ...]

The same as :attr:path: ('a', '1', 'i').

occurrence property

occurrence: int | None

Which paragraph with this marker it is among its siblings, 1 for the first, if the marker repeats (definitions sections repeat "(1)"); otherwise None.

heading property

heading: str

The italic run-in heading, e.g. "Standard: Minimum necessary".

own_text property

own_text: str

This paragraph's own Markdown, without its subparagraphs.

For (k) in (k) Standard—(1) ... (2) ..., the text up to (1).

Part

Part(element: Element, parent: Node | None, source: Source)

Bases: Division

A part: the rules on one subject, e.g. 45 CFR Part 164.

Section

Section(
    element: Element, parent: Node | None, source: Source
)

Bases: Division

A section, e.g. 45 CFR 164.502; its children are its top paragraphs.

children property

children: tuple[Node, ...]

Top-level paragraphs: (a), (b), ...

paragraph_issues property

paragraph_issues: tuple[str, ...]

Irregularities found while rebuilding the paragraph tree.

Empty when every paragraph sequence runs (a), (b), (c)... without gaps or repeats. Otherwise lookups in this section deserve a second look; :meth:to_markdown is faithful either way.

Subchapter

Subchapter(
    element: Element, parent: Node | None, source: Source
)

Bases: Division

A subchapter of a chapter, e.g. 45 CFR Subchapter C.

SubjectGroup

SubjectGroup(
    element: Element, parent: Node | None, source: Source
)

Bases: Division

An unnumbered group of sections, cited like the eCFR: " - ".

Subpart

Subpart(
    element: Element, parent: Node | None, source: Source
)

Bases: Division

A subpart of a part, e.g. 45 CFR Part 164 Subpart E.

Subtitle

Subtitle(
    element: Element, parent: Node | None, source: Source
)

Bases: Division

A subtitle of a title, e.g. 45 CFR Subtitle A.

Title

Title(
    element: Element, parent: Node | None, source: Source
)

Bases: Division

A CFR title, e.g. Title 45—Public Welfare.

AmbiguousNodeError

AmbiguousNodeError(message: str, candidates: list)

Bases: ECFRError, LookupError

Several nodes match a lookup.

candidates holds every match, in document order.

APIError

APIError(response: Response)

Bases: ECFRError

The API answered with an HTTP error status.

BadRequestError

BadRequestError(response: Response)

Bases: APIError

HTTP 400: the API rejected the request parameters.

DateOutOfRangeError

Bases: InvalidParameterError

The requested date is outside the range the eCFR has content for.

ECFRConnectionError

Bases: ECFRError

The API could not be reached (DNS, TLS, connection reset, ...).

ECFRError

Bases: Exception

Base class for all ecfr-md errors.

ECFRTimeoutError

Bases: ECFRConnectionError

The API did not respond within the configured timeout.

ECFRWarning

Bases: UserWarning

The data may be incomplete or in flux, e.g. during an eCFR import.

InvalidCitationError

Bases: InvalidParameterError

A citation such as 45 CFR 164.502 could not be understood.

InvalidParameterError

Bases: ECFRError, ValueError

A request parameter failed validation before being sent.

MissingDependencyError

Bases: ECFRError, ImportError

An export format needs an optional extra that isn't installed.

The message says how to install it.

NodeNotFoundError

Bases: ECFRError, KeyError

No child, descendant or paragraph matches the requested identifier.

NotFoundError

NotFoundError(response: Response)

Bases: APIError

HTTP 404: no content matches the request.

RateLimitError

RateLimitError(response: Response)

Bases: APIError

HTTP 429: too many requests.

ResponseFormatError

Bases: ECFRError

The API returned a body that could not be parsed as expected.

ServerError

ServerError(response: Response)

Bases: APIError

HTTP 5xx: the API failed or is temporarily unavailable.

TitleNotFoundError

Bases: ECFRError, LookupError

The requested CFR title does not exist or has no content.

Hierarchy

Bases: TypedDict

Location within a CFR title. Omit everything to select the whole title.

Attributes

subtitle: str Subtitle, an uppercase letter, e.g. 'A'. chapter: str Chapter, roman numerals or digits, e.g. 'I'. subchapter: str Subchapter, e.g. 'C'. The API's full text ignores subtitle, chapter and subchapter and returns the whole title; ecfr-md get and save cut them out of it. part: str Part, e.g. '164'. subpart: str Subpart, e.g. 'E'. section: str Section, e.g. '164.502'. appendix: str Full appendix name, e.g. 'Appendix A to Subpart C of Part 164'.

SearchFilters

Bases: TypedDict

Filters accepted by every search endpoint.

Attributes

within: str Limit to a title or any part of it, given as a citation, e.g. "45 CFR Part 164" or "21 CFR 11". agency_slugs: list[str] Limit to content associated with these agencies: slugs such as health-and-human-services-department (see ecfr-md api admin agencies). date: DateLike Limit to content present on this date. last_modified_after: DateLike Limit to content last modified after this date. last_modified_on_or_after: DateLike Limit to content last modified on or after this date. last_modified_before: DateLike Limit to content last modified before this date. last_modified_on_or_before: DateLike Limit to content last modified on or before this date.

Passage dataclass

Passage(
    node: Node,
    text: str,
    start: int,
    end: int,
    total: int,
    tokens: int,
    total_tokens: int,
    paragraphs: list[Node] = list(),
)

A slice of a node's text that fits a budget.

start and end are offsets in the node's Markdown; total is its length. cursor continues where this passage ends, None at the end of the text.

complete property

complete: bool

The passage is all of the text.

more property

more: bool

Text follows this passage.

cursor property

cursor: str | None

Where to continue: the node's URI with the offset, e.g. cfr:45/164.502@2024-01-01#5120; None at the end.

QuoteCheck dataclass

QuoteCheck(
    quote: str,
    citation: str,
    address: str | None,
    found: bool,
    cited: bool,
    similarity: float,
    matched: str,
    url: str | None = None,
    date: str | None = None,
)

Whether a quote is in a citation's text.

found is true when the quote is there word for word (ignoring formatting, whitespace, quote marks, dashes and paragraph labels); cited when it's also within the citation given. citation is the pinpoint of the match, or of the nearest passage when not found, whose similarity (0 to 1) says how alike it is; matched is that text.

verified property

verified: bool

Found word for word, at the citation given.

differences

differences() -> list[tuple[Literal['=', '-', '+'], str]]

Word by word, from the quote to the text: kept ("="), only in the quote ("-") and only in the text ("+").

Progress

fetching

fetching(citation: str, date: date) -> None

Regulation text for citation as of date is being fetched.

started

started(url: str) -> None

A request was sent.

received

received(url: str, done: int, total: int | None) -> None

done bytes of a response have arrived (total if known).

finished

finished(url: str, size: int, *, cached: bool) -> None

A response is complete, or was read from the cache.

retrying

retrying(
    url: str,
    error: Exception,
    delay: float,
    attempt: int,
    attempts: int,
) -> None

A request failed and will be retried after delay seconds.

rate_changed

rate_changed(rate: float | None) -> None

The request rate limit changed (requests per second; None = none).

parts_started

parts_started(total: int) -> None

Text is being fetched one part at a time, total parts in all.

part_finished

part_finished(identifier: str) -> None

One part has been fetched.

file_written

file_written(path: Path) -> None

A Markdown file was written.

Reference dataclass

Reference(
    start: int,
    end: int,
    text: str,
    target: Address | None,
    url: str,
    kind: Kind = "cfr",
)

A citation found in text: where it is, and what it points to.

target is the CFR place for kind == "cfr", else None; url is the eCFR page, or the official site of the U.S. Code ("usc"), the Federal Register ("fr") or public laws ("public_law").

citation property

citation: str

The target's citation, e.g. "45 CFR 164.501"; else the text.

to_dict

to_dict() -> dict[str, Any]

JSON-ready: start, end, text, kind, citation, address (None outside the CFR) and url.

Change dataclass

Change(
    citation: str,
    identifier: str,
    heading: str,
    issued: date,
    effective: date,
    kind: Literal["substantive", "editorial", "removed"],
    raw: ContentVersion,
    site: str = SITE_URL,
)

A version of a section or appendix the eCFR issued.

citation instance-attribute

citation: str

E.g. "45 CFR 164.502".

heading instance-attribute

heading: str

The heading without its number, e.g. "Uses and disclosures of ...".

issued instance-attribute

issued: date

When the eCFR published the change.

effective instance-attribute

effective: date

When the change took effect.

site class-attribute instance-attribute

site: str = field(default=SITE_URL, repr=False)

The eCFR web site url links to.

level property

level: Level | str

Level.SECTION or Level.APPENDIX.

address property

address: str

The section or appendix changed, e.g. "45/164.502".

uri property

uri: str

The address as of this change, e.g. "cfr:45/164.502@2024-01-01".

url property

url: str

The eCFR page showing the text as of this change.

to_dict

to_dict(*, include_raw: bool = False) -> dict[str, Any]

This change as a dict ready for json.dumps.

Keys: citation, address, uri, level, identifier, heading, date (when it took effect, ISO format), url, issued, effective and kind; with include_raw, also raw, the API's version.

Match dataclass

Match(
    citation: str,
    heading: str,
    excerpt: str,
    starts_on: date,
    ends_on: date | None,
    raw: SearchResult,
    site: str = SITE_URL,
)

A section or appendix that matches a search.

citation instance-attribute

citation: str

E.g. "45 CFR 164.514"; pass it to get.

excerpt instance-attribute

excerpt: str

Text around the matching words, without markup.

ends_on instance-attribute

ends_on: date | None

When this text was replaced, or None if it is current.

site class-attribute instance-attribute

site: str = field(default=SITE_URL, repr=False)

The eCFR web site url links to.

identifier property

identifier: str

The section number or appendix name, e.g. "164.514".

level property

level: Level

Level.SECTION or Level.APPENDIX.

address property

address: str

The section or appendix, e.g. "45/164.514".

uri property

uri: str

The address as of starts_on, e.g. "cfr:45/164.514@2024-01-01".

url property

url: str

The eCFR page showing the matching text, as of starts_on.

to_dict

to_dict(*, include_raw: bool = False) -> dict[str, Any]

This match as a dict ready for json.dumps.

Keys: citation, address, uri, level, identifier, heading, date (starts_on, ISO format), url, excerpt, starts_on and ends_on (None if current); with include_raw, also raw, the API's search result.

Matches

Matches(
    matches: Iterable[Match] = (),
    total: int | None = None,
    *,
    complete: bool = False,
    query: str = "",
    exact: int | None = None,
    note: str = "",
)

Bases: list[Match]

Search matches, best first, one per section.

total is how many matching versions the eCFR counted: a section that matches in several versions counts several times. complete is true when every match is in the list. query is what was last sent to the eCFR; exact how many of the first matches have the exact phrase, when plain words were searched as a phrase and then as words; note says when the search was widened to find anything.

to_dict

to_dict() -> dict[str, Any]

JSON-ready: the matches, and whether more exist.

Outline dataclass

Outline(
    level: Level | str,
    identifier: str | None,
    heading: str,
    citation: str,
    reserved: bool,
    size: int | None,
    _structure: Structure,
    _children: tuple[Outline, ...] | None = (),
    date: date | None = None,
    url: str = "",
    address: str = "",
)

An entry in a table of contents, with its children.

Iterate over it for its children; index it like a node, by position or identifier at any depth: outline["Subpart E"], outline["164.512"]. str(outline) is the indented table of contents.

Outlines from a client can look beyond themselves: next and previous are the neighbouring sections or appendices, across parts, chapters and titles; up and siblings work at the top of the outline too; read() fetches the text.

level instance-attribute

level: Level | str

A :class:Level such as Level.PART; a plain string for entries the eCFR gives other types, such as unnumbered headings ("hed1").

heading instance-attribute

heading: str

The label without markup, e.g. "Part 164—Security and Privacy".

size instance-attribute

size: int | None

Size of the full text in bytes, where the eCFR gives it (parts).

date class-attribute instance-attribute

date: date | None = None

The point-in-time date of the outline, if known.

url class-attribute instance-attribute

url: str = field(default='', repr=False)

The eCFR web page for this entry.

address class-attribute instance-attribute

address: str = field(default='', repr=False)

The entry's address, e.g. "45/part-164/subpart-E".

children property

children: tuple[Outline, ...]

The entries inside this one, in document order.

parent property

parent: Outline | None

The entry this one is in, or None at the top of the outline.

raw property

raw: Node

The API's structure node for this entry, with everything below it.

up property

up: Outline | None

The entry this one is in, even at the top of this outline (a part's chapter, a title's CFR); None for the whole CFR.

siblings property

siblings: tuple[Outline, ...]

The other entries in the same parent, in document order.

next property

next: Outline | None

The next section or appendix after this entry, in document order, crossing into the next part, chapter or title; None at the end. Reserved sections are skipped.

previous property

previous: Outline | None

The section or appendix before this entry, in document order.

ancestors property

ancestors: tuple[Outline, ...]

Parent, grandparent, ... up to the top of the outline.

uri property

uri: str

The address at the outline's date, e.g. "cfr:45/part-164@2024-01-01".

build classmethod

build(
    node: Structure | Node,
    title: int,
    hierarchy: Mapping[str, object] | None = None,
    parent: Outline | None = None,
    *,
    date: date | None = None,
    site: str = SITE_URL,
) -> Outline

An outline from the API's structure, with citations and links.

whole classmethod

whole(
    titles: Iterable[TitleInfo],
    date: date | None,
    load: Callable[[int, date], Structure],
    site: str = SITE_URL,
) -> Outline

The outline of the whole CFR: one entry per title, each opened (its structure loaded with load) the first time it's used.

date is the point in time, or None for each title's latest text.

read

read(date: DateLike | None = None) -> Node

The text of this entry, as of date (default: the outline's date).

__getitem__

__getitem__(key: str | int | Address) -> Outline

A child by position, or the nearest entry by identifier.

Keys can name their level ("Subpart E", "§ 164.512"), be citations ("45 CFR 164.512") or addresses, relative or not ("subpart-E", "45/164.512"). Raises NodeNotFoundError if nothing matches and AmbiguousNodeError if several entries match at the nearest depth.

get

get(
    key: str | int | Address, default: Outline | None = None
) -> Outline | None

Like outline[key], but return default when nothing matches.

iter

iter(
    level: Level | LevelName | None = None,
) -> Iterator[Outline]

Every entry below this one in document order, optionally one level.

Level names are case-insensitive; an unknown one raises InvalidParameterError.

find

find(
    identifier: str | None = None,
    *,
    level: Level | LevelName | None = None,
) -> Outline | None

The first entry below this one (nearest, then in document order) that matches, or None. Unlike outline[...], it needn't be unique.

to_dict

to_dict(
    *, depth: int | None = None, include_raw: bool = False
) -> dict[str, Any]

This entry as a dict ready for json.dumps.

Keys: citation, address, uri, level, identifier, heading, date (ISO format, or None), url, reserved, size and children.

Parameters

depth: int | None Levels of children to include; 0 leaves out children. Defaults to all of them. include_raw: bool Include raw: the API's structure node, as JSON-ready data.

TitleInfo dataclass

TitleInfo(
    number: int,
    name: str,
    latest: date | None,
    amended: date | None,
    reserved: bool,
    processing: bool,
    raw: Title,
    site: str = SITE_URL,
)

A CFR title, and how current the eCFR's text of it is.

name instance-attribute

name: str

E.g. "Public Welfare".

latest instance-attribute

latest: date | None

The latest date the eCFR has text for; None for reserved titles.

amended instance-attribute

amended: date | None

When the latest amendment took effect.

processing instance-attribute

processing: bool

The eCFR is applying updates, so the latest text may still change.

site class-attribute instance-attribute

site: str = field(default=SITE_URL, repr=False)

The eCFR web site url links to.

citation property

citation: str

E.g. "45 CFR".

address property

address: str

E.g. "45".

uri property

uri: str

The title at its latest date, e.g. "cfr:45@2024-01-01".

url property

url: str

The title's eCFR page.

to_dict

to_dict(*, include_raw: bool = False) -> dict[str, Any]

This title as a dict ready for json.dumps.

Keys: citation, address, uri, level ("title"), identifier, heading (the name), date (latest, ISO format), url, amended, reserved and processing; with include_raw, also raw.

SyncResult dataclass

SyncResult(
    added: list[Path] = list(),
    changed: list[Path] = list(),
    removed: list[Path] = list(),
    unchanged: list[Path] = list(),
    kept: list[Path] = list(),
    modified: list[Path] = list(),
    moved: list[tuple[Path, Path]] = list(),
)

What sync did, or with dry_run would do, to each file.

kept holds snapshots saved with a past date (files, or a tree's top folder), left at that date. modified holds files edited since they were saved, left as they are. moved holds (old, new) paths of files renamed to today's layout by migrate.

load

load(
    xml: bytes | str,
    *,
    title: int,
    date: date | None = None,
    hierarchy: Hierarchy | None = None,
    url: str | None = None,
    retrieved: datetime | None = None,
    pinned: bool = False,
) -> Division

Build a navigable document from eCFR XML (e.g. versioner.full).

url and retrieved record where and when the XML was fetched; they appear in saved files' front matter. pinned marks text as of a date older than the latest, which sync keeps at that date.

find_references

find_references(
    text: str,
    context: Address | str | int | None = None,
    *,
    urls: Mapping[str, str] | None = None,
    markdown: bool = False,
    site: str = SITE_URL,
) -> list[Reference]

Cross-references in text, in order.

context is where the text is: an address or citation such as 45/164.502 (its title, part, subpart and section resolve relative references, and its date dates the links). Without it, only references that name their title ("45 CFR 160.103") and other codes are found. urls overrides the link templates: keys "usc", "fr" and "public_law". With markdown, headings, links, HTML tags and code are skipped. CFR references link to pages on site.

configure

configure(
    settings: Settings | None = None, /, **fields: Any
) -> ECFR

Change the settings of the client the module-level functions share.

Give a :class:~ecfr_md.config.Settings, or settings by name, which win over ECFR_MD_* variables and the config file, as with Settings.load(**fields)::

ecfr_md.configure(site_url="https://mirror.example", source="api")

The client in use before is closed. Returns the new one.