-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfilter_users.py
More file actions
266 lines (208 loc) · 7.57 KB
/
Copy pathfilter_users.py
File metadata and controls
266 lines (208 loc) · 7.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
"""User filtering CLI: filter by name, age, or email.
Usage examples:
python users_filter.py --file users.json --by name --query "Alice"
python users_filter.py --file users.json --by age --query ">=18"
python users_filter.py --file users.json --by email --query "@example.com"
If --by / --query are omitted, the script will prompt interactively.
"""
from __future__ import annotations
import argparse
import json
import operator
from pathlib import Path
from typing import Any, Callable, List, Optional, TypedDict
# ----------------------------- Types & Schema -------------------------------
class User(TypedDict, total=False):
"""Minimal expected user schema in users.json."""
name: str
age: int
email: str
# ----------------------------- I/O & Utilities ------------------------------
def read_users(file_path: str | Path) -> List[User]:
"""Load users from a JSON file; return [] on error or wrong shape."""
try:
p = Path(file_path)
with p.open("r", encoding="utf-8") as f:
data = json.load(f)
return data if isinstance(data, list) else []
except (OSError, json.JSONDecodeError) as exc:
print(f"Error loading {file_path}: {exc}")
return []
def print_users(users: List[User]) -> None:
"""Pretty-print users, one JSON object per line."""
for user in users:
print(json.dumps(user, ensure_ascii=False))
def _normalize_str(value: Any) -> Optional[str]:
"""Return a trimmed string or None if not a non-empty string."""
if isinstance(value, str):
s = value.strip()
return s if s else None
return None
def _to_int(value: Any) -> Optional[int]:
"""Coerce age-like values to int (int, integral float, or digit-string)."""
if isinstance(value, int):
return value
if isinstance(value, float) and value.is_integer():
return int(value)
if isinstance(value, str) and value.strip().isdigit():
return int(value.strip())
return None
# ----------------------------- Age Filter Parser ----------------------------
def _parse_age_filter(expr: str) -> Callable[[Any], bool]:
"""Build a predicate from '30', '>=18', '<21', '20-29', '30+'."""
s = (_normalize_str(expr) or "").replace(" ", "")
# range: "a-b"
if "-" in s and not s.startswith("-"):
left, right = s.split("-", 1)
try:
a, b = int(left), int(right)
except ValueError:
return lambda _age: False
def pred(age: Any) -> bool:
n = _to_int(age)
return n is not None and a <= n <= b
return pred
# "n+" shorthand
if s.endswith("+"):
try:
n_min = int(s[:-1])
except ValueError:
return lambda _age: False
def pred(age: Any) -> bool:
n = _to_int(age)
return n is not None and n >= n_min
return pred
# comparators
for op_str, op_fn in ((">=", operator.ge), ("<=", operator.le),
(">", operator.gt), ("<", operator.lt)):
if s.startswith(op_str):
try:
n_ref = int(s[len(op_str):])
except ValueError:
return lambda _age: False
def pred(age: Any, n=n_ref, cmp=op_fn) -> bool:
v = _to_int(age)
return v is not None and cmp(v, n)
return pred
# exact int
try:
n_exact = int(s)
except ValueError:
return lambda _age: False
def pred(age: Any, n=n_exact) -> bool:
v = _to_int(age)
return v is not None and v == n
return pred
# ----------------------------- Filter Functions -----------------------------
def filter_users_by_name(users: List[User], name: str) -> List[User]:
"""Return users whose name matches exactly (case-insensitive)."""
needle = _normalize_str(name)
if not needle:
return []
needle_l = needle.lower()
return [
u for u in users
if isinstance(u.get("name"), str)
and u["name"].strip().lower() == needle_l
]
def filter_users_by_age(users: List[User], age_expression: str) -> List[User]:
"""Filter users by age using expressions like '30', '>=18', '<21', '20-29', '30+'."""
pred = _parse_age_filter(age_expression)
return [u for u in users if pred(u.get("age"))]
def filter_users_by_email(users: List[User], query: str) -> List[User]:
"""Filter by email (case-insensitive).
Supported queries:
- Exact address: "alice@example.com"
- Domain only: "@example.com" or "example.com"
"""
q = _normalize_str(query)
if not q:
return []
q_l = q.lower()
results: List[User] = []
for u in users:
email = u.get("email")
if not isinstance(email, str):
continue
e = email.strip().lower()
if not e or "@" not in e:
continue
_local, _at, domain = e.partition("@")
# Domain-only: "@example.com"
if q_l.startswith("@"):
dom_q = q_l[1:]
if dom_q and domain == dom_q:
results.append(u)
continue
# Domain-only: "example.com"
if "@" not in q_l:
if domain == q_l:
results.append(u)
continue
# Exact address
if e == q_l:
results.append(u)
return results
# --------------------------------- CLI --------------------------------------
def _build_arg_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
description="Filter users (from users.json) by name, age, or email."
)
parser.add_argument(
"--file", "-f", default="users.json",
help="Path to users JSON file (default: users.json)",
)
parser.add_argument(
"--by", "-b", choices=("name", "age", "email"),
help="Filter category to use.",
)
parser.add_argument(
"--query", "-q",
help="Filter value. Examples: 'Alice' | '>=18' | '20-29' | '@example.com'.",
)
parser.add_argument(
"--interactive", "-i", action="store_true",
help="Prompt for missing values (if --by/--query not provided).",
)
return parser
def _prompt_missing(by: str | None, query: str | None) -> tuple[str, str]:
"""Ask user for missing --by/--query interactively."""
if not by:
while True:
by = input("Filter by ('name', 'age', 'email'): ").strip().lower()
if by in {"name", "age", "email"}:
break
print("Please choose one of: name, age, email.")
if not query:
if by == "name":
query = input("Enter name (exact match): ").strip()
elif by == "age":
query = input(
"Enter age filter (e.g., '30', '>=18', '<21', '20-29', '30+'): "
).strip()
else:
query = input(
"Enter email or domain (e.g., 'alice@example.com', "
"'@example.com', 'example.com'): "
).strip()
return by, query
def main() -> None:
parser = _build_arg_parser()
args = parser.parse_args()
# Interactive fallback if requested or if required args are missing
by = args.by
query = args.query
if args.interactive or not by or not query:
by, query = _prompt_missing(by, query)
users = read_users(args.file)
if not users:
return
if by == "name":
result = filter_users_by_name(users, query)
elif by == "age":
result = filter_users_by_age(users, query)
else:
result = filter_users_by_email(users, query)
print_users(result)
if __name__ == "__main__":
main()