cattrs does not unstructure os.PathLike to str

Open
#417 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
3/5
Estimated time
1-2 days
Newbie friendliness
42/100
Issue type
Bug
Clarity
Mostly clear
Activity status
Stale
Tech stack
python
Domain
tooling

Research direction

Start by reproducing the example with cattrs 23.1.2 and inspect how unstructuring handles the os.PathLike annotation compared with pathlib.Path and Union[str, os.PathLike]. The issue is resolved when the bar field is unstructured to a string consistently and a regression test covers the reported example.

Written by the indexing model from the issue text.

Description

  • cattrs version: 23.1.2
  • Python version: 3.11.3
  • Operating System: Arch Linux
Description

When unstructuring an attrs class where one of the fields is annotated as os.PathLike (and contains a Path), that field remains a Path (in my case, PosixPath) instead of being unstructured as str.

Curiously, annotating the field as Union[str, os.PathLike] or pathlib.Path (without changing the actual data type) resolves the issue.

What I Did
In [1]: import os
   ...: from pathlib import Path
   ...: from typing import Union
   ...: 
   ...: import attrs
   ...: import cattrs
   ...: import cattrs.preconf.json

In [2]: @attrs.define
   ...: class MyClass:
   ...:     foo: Union[str, os.PathLike] = Path("/foo")
   ...:     bar: os.PathLike = Path("/bar")
   ...: 

In [3]: cattrs.preconf.json.make_converter().unstructure(MyClass())
Out[3]: {'foo': '/foo', 'bar': PosixPath('/bar')}

In [4]: cattrs.unstructure(MyClass())
Out[4]: {'foo': '/foo', 'bar': PosixPath('/bar')}

I'm not saying that this must be a bug (rather than merely my mis-usage of cattrs), but I was not able to find anything in the docs that would suggest that I was doing something incorrectly.

Dominant language
Python
Stars
1.1k
Forks
159
Avg merge
12h 21m
Merged PRs (30d)
6

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from python-attrs/cattrs

All issues in python-attrs/cattrs

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.