fpathlib 0.1.3.dev0__py3-none-any.whl → 0.1.4.dev16__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
fpathlib/__init__.py CHANGED
@@ -2,6 +2,7 @@ from fpathlib.path import Path
2
2
  from fpathlib.fpath import FPath, ExpandedFPath
3
3
  from fpathlib.expand import (
4
4
  expand_fpath,
5
+ iexpand_fpath,
5
6
  expand_fpath_decorator,
6
7
  is_expandable,
7
8
  )
@@ -11,6 +12,7 @@ __all__ = [
11
12
  "FPath",
12
13
  "ExpandedFPath",
13
14
  "expand_fpath",
15
+ "iexpand_fpath",
14
16
  "expand_fpath_decorator",
15
17
  "is_expandable",
16
18
  ]
fpathlib/_version.py CHANGED
@@ -18,7 +18,7 @@ version_tuple: tuple[int | str, ...]
18
18
  commit_id: str | None
19
19
  __commit_id__: str | None
20
20
 
21
- __version__ = version = '0.1.3.dev0'
22
- __version_tuple__ = version_tuple = (0, 1, 3, 'dev0')
21
+ __version__ = version = '0.1.4.dev16'
22
+ __version_tuple__ = version_tuple = (0, 1, 4, 'dev16')
23
23
 
24
24
  __commit_id__ = commit_id = None
fpathlib/expand.py CHANGED
@@ -31,6 +31,38 @@ def expand_fpath(fpath, *, exclude_path_patterns=None, require_metadata=True):
31
31
  )
32
32
 
33
33
 
34
+ def iexpand_fpath(fpath, *, exclude_path_patterns=None, require_metadata=True, errors="raise"):
35
+ """
36
+ Generator equivalent of :func:`.expand_fpath` -- lazily yields each
37
+ matching :obj:`.Path` instead of building the whole
38
+ :obj:`.ExpandedFPath` up front. This is a convenience function that
39
+ simply creates an :obj:`FPath` and calls its :meth:`.FPath.iexpand`
40
+ method.
41
+
42
+ Parameters
43
+ ----------
44
+ fpath : :obj:`str`
45
+ An f-string path, where the variables are captured and stored along the path
46
+ name.
47
+ exclude_path_patterns : :obj:`str` or :obj:`Iterable`[:obj:`str`]
48
+ Exclude paths that match the supplied pattern. (Default: None).
49
+ require_metadata : :obj:`bool`
50
+ Require that all paths identified must have found metadata. (Default: True).
51
+ errors : :obj:`str`
52
+ How to handle the "no matches" case. See :meth:`.FPath.iexpand`. (Default: "raise").
53
+
54
+ Yields
55
+ ------
56
+ :obj:`.Path`
57
+ """
58
+
59
+ return FPath(fpath).iexpand(
60
+ exclude_path_patterns=exclude_path_patterns,
61
+ require_metadata=require_metadata,
62
+ errors=errors,
63
+ )
64
+
65
+
34
66
  def expand_fpath_decorator(f=None, require_expandable=True, post_process=None):
35
67
  """
36
68
  Decorator for :func:`.expand_fpath`.
@@ -88,7 +120,8 @@ def expand_fpath_decorator(f=None, require_expandable=True, post_process=None):
88
120
 
89
121
  def is_expandable(fpath):
90
122
  """
91
- Check if expandable.
123
+ Check whether `fpath` has fpathlib's own named f-string captures (e.g.
124
+ `{name}`).
92
125
 
93
126
  Parameters
94
127
  ----------
fpathlib/ext/polars.py CHANGED
@@ -169,6 +169,7 @@ def scan_txt(
169
169
  has_header=False,
170
170
  keep_line=False,
171
171
  usecols=None,
172
+ validate_schema=True,
172
173
  *args,
173
174
  **kwargs,
174
175
  ):
@@ -198,6 +199,17 @@ def scan_txt(
198
199
  Whether to keep the original line as a column in the output.
199
200
  usecols : :obj:`list`[:obj:`int`], optional
200
201
  Indexes of columns to keep in the output. If not provided, all columns are kept. Only applicable if `separator` is provided.
202
+ validate_schema : :obj:`bool`
203
+ When the field count is inferred from a single representative file
204
+ (the fast path for a multi-file glob/pattern), also check that no
205
+ *other* matched file has *more* fields than that sample. A file with
206
+ fewer fields than the sample already raises a clear polars error
207
+ (out-of-bounds list access); a file with more fields would otherwise
208
+ have its extra columns silently dropped instead of erroring. This
209
+ check reads every matched file's line count, which costs an extra
210
+ full pass over the data on top of the fast path -- pass False if
211
+ you've already confirmed your files are consistent and want to
212
+ skip it for speed on very large globs. (Default: True)
201
213
  *args
202
214
  Positional arguments to pass to :meth:`polars.scan_csv`.
203
215
  **kwargs
@@ -282,6 +294,26 @@ def scan_txt(
282
294
  # Initial field names, may be renamed later from header or by `new_columns`
283
295
  fields = {i: f"field_{i}" for i in range(n_fields)}
284
296
 
297
+ # n_fields came from a single sample file (see above), so a file
298
+ # with *fewer* fields than the sample will already raise a clear
299
+ # polars error below (list.get() on an out-of-bounds index). A
300
+ # file with *more* fields would not -- its extra columns would
301
+ # just be silently dropped -- so check for that explicitly if
302
+ # requested.
303
+ if validate_schema and sample_schema is not None:
304
+ max_fields = (
305
+ lf.select(_polars.col("fields").list.len().max())
306
+ .collect()
307
+ .item()
308
+ )
309
+ if max_fields is not None and max_fields > n_fields:
310
+ msg = (
311
+ f"field count mismatch: schema was inferred from a "
312
+ f"single sample file with {n_fields} fields, but at "
313
+ f"least one matched file has {max_fields} fields"
314
+ )
315
+ raise ValueError(msg)
316
+
285
317
  # Add each field as a separate column
286
318
  for i, field in fields.items():
287
319
  lf = lf.with_columns(_polars.col("fields").list.get(i).alias(field))
fpathlib/fpath.py CHANGED
@@ -1,5 +1,5 @@
1
1
  from collections.abc import Sequence
2
- from glob import glob
2
+ from glob import glob, iglob
3
3
  import parse
4
4
  import re
5
5
 
@@ -31,10 +31,19 @@ class FPath:
31
31
  def __repr__(self):
32
32
  return "FPath({!r})".format(self.fpath)
33
33
 
34
- def expand(self, exclude_path_patterns=None, require_metadata=True, errors="raise"):
34
+ def iexpand(self, exclude_path_patterns=None, require_metadata=True, errors="raise"):
35
35
  """
36
- Use an f-string to extract out a collection of paths, where the f-string
37
- variables are captured and stored along the path name.
36
+ Lazily yield each :obj:`.Path` matching the f-string pattern, one at
37
+ a time, instead of building the whole :obj:`.ExpandedFPath` up
38
+ front. Useful when a pattern could match a very large number of
39
+ files and you don't want them all held in memory at once, or want
40
+ to start processing before the full glob finishes walking the
41
+ filesystem. :meth:`.expand` is built on top of this generator.
42
+
43
+ Like any generator function, nothing in the body runs -- including
44
+ argument validation and the wildcard/{} capture check -- until the
45
+ result is first iterated (a `for` loop, `list(...)`, etc.), not at
46
+ the moment :meth:`.iexpand` is called.
38
47
 
39
48
  Parameters
40
49
  ----------
@@ -43,13 +52,13 @@ class FPath:
43
52
  require_metadata : :obj:`bool`
44
53
  Require that all paths identified must have found metadata. (Default: True).
45
54
  errors : :obj:`str`
46
- How to handle errors. If "raise", then raise an error. If "warn", then warn
47
- and return an empty collection. If "ignore", then ignore the error and
48
- return an empty collection. (Default: "raise").
55
+ How to handle the "no matches" case, checked once the pattern is
56
+ fully exhausted. If "raise", then raise an error. If "warn",
57
+ then warn. If "ignore", then do nothing. (Default: "raise").
49
58
 
50
- Returns
51
- -------
52
- :obj:`.ExpandedFPath`
59
+ Yields
60
+ ------
61
+ :obj:`.Path`
53
62
  """
54
63
 
55
64
  if errors not in {"raise", "warn", "ignore"}:
@@ -58,8 +67,34 @@ class FPath:
58
67
 
59
68
  parser = parse.compile(self.fpath)
60
69
 
61
- paths = []
62
- for fname in glob(re.sub(r"\{.*?\}", "*", self.fpath)):
70
+ # glob() (used below to find files) and `parse` (used above to
71
+ # extract {name} values) disagree about what a bare '*', '?', or
72
+ # '[...]' means outside a {} capture: glob treats it as a wildcard,
73
+ # but parse's format-string language only special-cases {...} and
74
+ # reads everything else -- including '*' -- as literal text to
75
+ # match. A pattern like "{a}/*" would find files fine via glob()
76
+ # but then fail to parse against that same string, since real
77
+ # filenames don't literally contain "/*" -- silently producing
78
+ # metadata=None for every match, or raising a confusing "metadata
79
+ # not found" error, with no indication that '*' was the actual
80
+ # problem. Fail fast and explain it instead. Only applies when
81
+ # there's a {} capture to begin with -- a plain glob with none is a
82
+ # separate, unaffected case (no metadata is expected from it).
83
+ if parser.named_fields:
84
+ literal_fpath = re.sub(r"\{.*?\}", "", self.fpath)
85
+ for c in "*?[":
86
+ if c in literal_fpath:
87
+ msg = (
88
+ f"glob wildcard {c!r} outside a {{}} capture is not "
89
+ f"supported in {self.fpath!r} -- 'parse' treats it "
90
+ "as a literal character, not a wildcard. Use a "
91
+ "named capture (e.g. '{a}/{b}') if you want that "
92
+ "segment captured too."
93
+ )
94
+ raise ValueError(msg)
95
+
96
+ n = 0
97
+ for fname in iglob(re.sub(r"\{.*?\}", "*", self.fpath)):
63
98
  path = Path(fname)
64
99
  if exclude_path_patterns and path.match_any(exclude_path_patterns):
65
100
  continue
@@ -67,9 +102,10 @@ class FPath:
67
102
  if require_metadata and path.metadata is None:
68
103
  msg = f"metadata not found for '{fname}' with '{self.fpath}'"
69
104
  raise AttributeError(msg)
70
- paths.append(path)
105
+ n += 1
106
+ yield path
71
107
 
72
- if len(paths) == 0 and errors != "ignore":
108
+ if n == 0 and errors != "ignore":
73
109
  msg = f"no paths found for {self.fpath.__repr__()}"
74
110
  if errors == "raise":
75
111
  raise IOError(msg)
@@ -78,6 +114,35 @@ class FPath:
78
114
 
79
115
  warnings.warn(msg)
80
116
 
117
+ def expand(self, exclude_path_patterns=None, require_metadata=True, errors="raise"):
118
+ """
119
+ Use an f-string to extract out a collection of paths, where the f-string
120
+ variables are captured and stored along the path name.
121
+
122
+ Parameters
123
+ ----------
124
+ exclude_path_patterns : :obj:`str` or :obj:`Iterable`[:obj:`str`]
125
+ Exclude paths that match the supplied pattern. (Default: None).
126
+ require_metadata : :obj:`bool`
127
+ Require that all paths identified must have found metadata. (Default: True).
128
+ errors : :obj:`str`
129
+ How to handle errors. If "raise", then raise an error. If "warn", then warn
130
+ and return an empty collection. If "ignore", then ignore the error and
131
+ return an empty collection. (Default: "raise").
132
+
133
+ Returns
134
+ -------
135
+ :obj:`.ExpandedFPath`
136
+ """
137
+
138
+ paths = list(
139
+ self.iexpand(
140
+ exclude_path_patterns=exclude_path_patterns,
141
+ require_metadata=require_metadata,
142
+ errors=errors,
143
+ )
144
+ )
145
+
81
146
  return ExpandedFPath(paths=paths, fpath=self)
82
147
 
83
148
 
@@ -153,7 +218,13 @@ class ExpandedFPath(Sequence):
153
218
 
154
219
  pl = import_optional_dependency("polars")
155
220
 
156
- data = [{"fname": str(key), **value} for key, value in self.metadata.items()]
221
+ # `value` is None whenever this ExpandedFPath was built with
222
+ # require_metadata=False and a path's metadata simply wasn't found
223
+ # (e.g. a plain glob with no named captures at all) -- treat that as
224
+ # "no metadata columns" rather than crashing on `**None`.
225
+ data = [
226
+ {"fname": str(key), **(value or {})} for key, value in self.metadata.items()
227
+ ]
157
228
  df = pl.DataFrame(data)
158
229
  if lazy:
159
230
  df = df.lazy()
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: fpathlib
3
- Version: 0.1.3.dev0
3
+ Version: 0.1.4.dev16
4
4
  Summary: A package to combine paths with metadata
5
5
  Author-email: "C. Lockhart" <clockha2@gmu.edu>
6
6
  Requires-Python: >=3.12
@@ -0,0 +1,13 @@
1
+ fpathlib/__init__.py,sha256=6HdQu7fISBIc6osLZp7CMJ65DW2aGNsvFCLKbUXgE10,348
2
+ fpathlib/_version.py,sha256=28sM26orIv-swz6NJDAQttdFakxmunN6hkOeiiQ6fYM,535
3
+ fpathlib/expand.py,sha256=31dMQxizf7SdZzDSv7UOfLkfwqsbzl_5JP1QbEeDR_0,4587
4
+ fpathlib/fpath.py,sha256=H7MnxyqE5N2wGu13ReBUjNg9WbSuV6PqEgtzV4uL3GU,8406
5
+ fpathlib/path.py,sha256=ME2jfMBCK1Emu35mu8wN-KvmPE4p8qQqX8q-uO5cDsI,2629
6
+ fpathlib/utils.py,sha256=os9ggFllqOZXYcjfKcxPIy92LuRfvt6jWL0gNfet1N0,545
7
+ fpathlib/ext/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ fpathlib/ext/polars.py,sha256=lamkEI1CKW0g1n6jvj0aJug-ypyNqa_H3vdTb6YfmIo,12819
9
+ fpathlib-0.1.4.dev16.dist-info/licenses/LICENSE,sha256=76rZ9i4ZumZ1M4jlYM9ZDOTYEeyzuxdsTKjF2qha3Lc,1069
10
+ fpathlib-0.1.4.dev16.dist-info/METADATA,sha256=lEBsRE0z0zJqVyXkgx5kM4257JIJAh91UCc8UZNH-qc,2142
11
+ fpathlib-0.1.4.dev16.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
12
+ fpathlib-0.1.4.dev16.dist-info/top_level.txt,sha256=QT5pDgO4--AJn7X4RB51xpNTt0pD5_U2mCjsydpQAQw,9
13
+ fpathlib-0.1.4.dev16.dist-info/RECORD,,
Binary file
Binary file
@@ -1,18 +0,0 @@
1
- fpathlib/__init__.py,sha256=VniZjNqT5pxzj6ymcpAlhNoWC44MwkQLu9jssc7o13Q,308
2
- fpathlib/_version.py,sha256=dxsNQZw4RtnKvRTjSi1emxt4lZsN7c7hbUngeAYGVZY,533
3
- fpathlib/expand.py,sha256=M_K1nfRAD9c983d68kCRuzo7-zNaOY_3R9gn8aBritI,3393
4
- fpathlib/fpath.py,sha256=okEgqpWQjearSyDTp6RdIWbFolijI3BrXR8F5t-9Was,4877
5
- fpathlib/path.py,sha256=ME2jfMBCK1Emu35mu8wN-KvmPE4p8qQqX8q-uO5cDsI,2629
6
- fpathlib/utils.py,sha256=os9ggFllqOZXYcjfKcxPIy92LuRfvt6jWL0gNfet1N0,545
7
- fpathlib/__pycache__/__init__.cpython-313.pyc,sha256=clLXRuVcvX9dJt4CTvaUBR6vhAzg67Ex7gKRwtumJFY,428
8
- fpathlib/__pycache__/path.cpython-313.pyc,sha256=mQVWw1qjmvUp3NflXzhC_Q654H4hFW29gLYHP9nxRPQ,12257
9
- fpathlib/__pycache__/utils.cpython-313.pyc,sha256=V4KSHMjm3ePQfaOKWwAkmaocvYb4VOul6Zooh0EvLa0,772
10
- fpathlib/ext/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
11
- fpathlib/ext/polars.py,sha256=r3-MoGfbB11cOrECGCEyFzdKXGGEI9DSV6Xfc8vHeJo,10994
12
- fpathlib/ext/__pycache__/__init__.cpython-313.pyc,sha256=lrgZbujuH_tlWGfe_Huo46srJdYJd1NQ6ZQFWamc6tc,153
13
- fpathlib/ext/__pycache__/polars.cpython-313.pyc,sha256=S0epPPABmHRj0IrCxyOC8hD2_g0hBKggFFWfsmXw4m0,7740
14
- fpathlib-0.1.3.dev0.dist-info/licenses/LICENSE,sha256=76rZ9i4ZumZ1M4jlYM9ZDOTYEeyzuxdsTKjF2qha3Lc,1069
15
- fpathlib-0.1.3.dev0.dist-info/METADATA,sha256=EqyLMoPqqdMHwjd0To4_dc-o-wW2B2t6HmHel926ueM,2141
16
- fpathlib-0.1.3.dev0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
17
- fpathlib-0.1.3.dev0.dist-info/top_level.txt,sha256=QT5pDgO4--AJn7X4RB51xpNTt0pD5_U2mCjsydpQAQw,9
18
- fpathlib-0.1.3.dev0.dist-info/RECORD,,