Skip to content

Commit

Permalink
Pydantic v2 compatibility (#119)
Browse files Browse the repository at this point in the history
* v2 compatibility

* add note to history
  • Loading branch information
pjbull authored Jul 18, 2023
1 parent 48c097a commit ce3e0ac
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 1 deletion.
4 changes: 4 additions & 0 deletions HISTORY.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# History

## 0.5.1 (2023-07-18)

- Add support for `pydantic>=2.0.0` ([PR #119](https://github.com/drivendataorg/nbautoexport/pull/119))

## 0.5.0 (2022-02-16)

- Removes support for Python 3.6.
Expand Down
14 changes: 14 additions & 0 deletions nbautoexport/sentinel.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,20 @@ class NbAutoexportConfig(BaseModel):
class Config:
extra = "forbid"

# deprecated in pydantic v2.0
def json(self, *args, **kwargs):
if hasattr(self, "model_dump_json"):
return self.model_dump_json(*args, **kwargs)
else:
return super().json(*args, **kwargs)

# deprecated in pydantic v2.0
def dict(self, *args, **kwargs):
if hasattr(self, "model_dump"):
return self.model_dump(*args, **kwargs)
else:
return super().dict(*args, **kwargs)


def install_sentinel(directory: Path, config: NbAutoexportConfig, overwrite: bool):
"""Writes the configuration file to a specified directory."""
Expand Down
11 changes: 11 additions & 0 deletions nbautoexport/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@ class JupyterNotebook(BaseModel):
path: Path
metadata: nbformat.notebooknode.NotebookNode

class Config:
# NotebookNode not pydantic v2 compatible
arbitrary_types_allowed = True

def get_script_extension(self):
# Match logic of nbconvert.exporters.script.ScriptExporter
# Order of precedence is: nb_convert_exporter, language, file_extension, .txt
Expand All @@ -53,6 +57,13 @@ def from_file(cls, path):
nbformat.validate(notebook)
return cls(path=path, metadata=notebook.metadata)

# deprecated in pydantic v2.0
def json(self, *args, **kwargs):
if hasattr(self, "model_dump_json"):
return self.model_dump_json(*args, **kwargs)
else:
return super().json(*args, **kwargs)

def __hash__(self):
return hash(self.json())

Expand Down
4 changes: 3 additions & 1 deletion tests/test_cli_configure.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,9 @@ def test_force_overwrite(tmp_path):
with (tmp_path / ".nbautoexport").open("r", encoding="utf-8") as fp:
config = json.load(fp)

expected_config = NbAutoexportConfig(export_formats=["script", "html"], organize_by="notebook")
expected_config = NbAutoexportConfig(
export_formats=["script", "html"], organize_by="notebook"
).dict()
assert config == expected_config


Expand Down

0 comments on commit ce3e0ac

Please sign in to comment.