gpt-4.1-mini-2025-04-14· openai
from WildChat-4.8M
python dataclass create static method to load from json
Private research annotation
Sign in to add a private research label or note.
- User
python dataclass create static method to load from json
- Assistant
Certainly! If you have a Python
dataclassand you want to create a static method to load an instance of that dataclass from a JSON string, you can do it as follows:pythonfrom dataclasses import dataclass import json @dataclass class Person: name: str age: int @staticmethod def from_json(json_str: str) -> "Person": data = json.loads(json_str) return Person(**data) # Example usage: json_data = '{"name": "Alice", "age": 30}' person = Person.from_json(json_data) print(person) # Person(name='Alice', age=30)Explanation:
- The
from_jsonstatic method receives a JSON string. - It uses
json.loadsto parse the JSON string into a dictionary. - Then it unpacks this dictionary as keyword arguments to the
Personconstructor.
Would you like an example with nested dataclasses or with type validation as well?
- The
- User
compute diff of a pytthon date pd.Series and test if all are equals to 1 days
- Assistant
You want to compute the difference between consecutive dates in a pandas Series of
datetimeobjects, and then test if all these differences are equal to 1 day.Here's how you can do it:
pythonimport pandas as pd # Example pd.Series of dates dates = pd.Series(pd.to_datetime([ '2023-01-01', '2023-01-02', '2023-01-03', '2023-01-04' ])) # Compute difference between consecutive dates diff = dates.diff() # Check if all differences (excluding first NaT) are equal to 1 day all_one_day = (diff.dropna() == pd.Timedelta('1 days')).all() print(all_one_day) # TrueExplanation:
dates.diff()will compute the difference between each date and the previous date, resulting in a Series ofTimedeltavalues.- The first element is because there is no previous element to subtract.