Data

YFPY module for retrieving, saving, and loading all Yahoo Fantasy Sports data.

This module is designed to allow for easy data management, such that both retrieving and managing Yahoo Fantasy Sports data can be done in one place without the need to manually run the queries and manage data saved to JSON files.

Example

The Data module can be used as follows::

yahoo_query = YahooFantasySportsQuery(
    "<league_id>",
    "<game_code>",
    game_id="<game_key>",
    yahoo_consumer_key=os.environ.get("YFPY_CONSUMER_KEY"),
    yahoo_consumer_secret=os.environ.get("YFPY_CONSUMER_SECRET"),
    all_output_as_json_str=False,
    browser_callback=True,
    offline=False
)

data_directory = Path(__file__).parent / "output"
data = Data(data_dir)
data.save("file_name", yahoo_query.get_all_yahoo_fantasy_game_keys)
data.load("file_name")
Attributes:
  • logger (Logger) –

    Module level logger for usage and debugging.

Data

Bases: object

YFPY Data object for Yahoo Fantasy Sports data retrieval, saving, and loading data as JSON.

Source code in yfpy/data.py
 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
class Data(object):
    """YFPY Data object for Yahoo Fantasy Sports data retrieval, saving, and loading data as JSON.
    """

    YFO = TypeVar("YFO", bound=YahooFantasyObject)

    def __init__(self, data_dir: Union[Path, str], save_data: bool = False, dev_offline: bool = False):
        """Instantiate data object to retrieve, save, and load Yahoo Fantasy Sports data.

        Args:
            data_dir (Path | str): Directory path where data will be saved/loaded.
            save_data (bool, optional): Boolean determining whether data is saved after retrieval from the Yahoo FF API.
            dev_offline (bool, optional): Boolean for offline development (requires a prior online run with
                save_data = True).

        """
        self.data_dir: Path = data_dir if isinstance(data_dir, PosixPath) else Path(data_dir)
        self.save_data: bool = save_data
        self.dev_offline: bool = dev_offline

    def update_data_dir(self, new_save_dir: Union[Path, str]) -> None:
        """Modify the data storage directory if it needs to be updated.

        Args:
            new_save_dir (str | Path): Full path to new desired directory where data will be saved/loaded.

        Returns:
            None

        """
        self.data_dir: Path = new_save_dir if isinstance(new_save_dir, PosixPath) else Path(new_save_dir)

    @staticmethod
    def fetch(yf_query: Callable,
              params: Union[Dict[str, str], None] = None) -> Union[str, YFO, List[YFO], Dict[str, YFO]]:
        """Run query to retrieve Yahoo Fantasy Sports data.

        Args:
            yf_query (Callable of YahooFantasySportsQuery): Chosen yfpy query method to run.
            params (dict of str: str, optional): Dictionary of parameters to be passed to chosen yfpy query function.

        Returns:
            object: Data retrieved by the yfpy query.

        """
        if params:
            return yf_query(**params)
        else:
            return yf_query()

    def save(self, file_name: str, yf_query: Callable, params: Union[Dict[str, Any], None] = None,
             new_data_dir: Union[Path, str, None] = None) -> Union[str, YFO, List[YFO], Dict[str, YFO]]:
        """Retrieve and save Yahoo Fantasy Sports data locally.

        Args:
            file_name (str): Name of file to which data will be saved.
            yf_query (Callable of YahooFantasySportsQuery): Chosen yfpy query method to run.
            params (dict of str: str, optional): Dictionary of parameters to be passed to chosen yfpy query function.
            new_data_dir (str | Path, optional): Full path to new desired directory to which data will be saved.

        Returns:
            object: Data retrieved by the yfpy query.

        """
        # change data save directory
        if new_data_dir:
            new_data_dir = new_data_dir if isinstance(new_data_dir, PosixPath) else Path(new_data_dir)
            logger.debug(f"Data directory changed from {self.data_dir} to {new_data_dir}.")
            self.update_data_dir(new_data_dir)

        # create full directory path if any directories in it do not already exist
        if not self.data_dir.exists():
            self.data_dir.mkdir(parents=True, exist_ok=True)

        # check if parent YahooFantasySportsQuery.all_output_as_json_str = True, unset it for data saving, then reset it
        all_output_as_json = False
        # noinspection PyUnresolvedReferences
        if yf_query.__self__.all_output_as_json_str:
            if inspect.ismethod(yf_query):
                # noinspection PyUnresolvedReferences
                for cls in inspect.getmro(yf_query.__self__.__class__):
                    if yf_query.__name__ in cls.__dict__:
                        # noinspection PyUnresolvedReferences
                        yf_query.__self__.all_output_as_json_str = False
                        all_output_as_json = True

        # run the actual yfpy query and retrieve the query results
        data = self.fetch(yf_query, params)

        # save the retrieved data locally
        saved_data_file_path = self.data_dir / f"{file_name}.json"
        with open(saved_data_file_path, "w", encoding="utf-8") as data_file:
            if isinstance(data, list):
                # unflatten list of object values to list of single-key dictionaries with object values if top level of
                # data to be saved is a list
                unnested_data = [{snakecase(el.__class__.__name__): el} for el in data]
            else:
                unnested_data = data

            jsonify_data_to_file(unnested_data, data_file)
        logger.debug(f"Data saved locally to: {saved_data_file_path}")

        # reset parent YahooFantasySportsQuery all_output_as_json_str = True and re-run query for json string return
        if all_output_as_json:
            # noinspection PyUnresolvedReferences
            yf_query.__self__.all_output_as_json_str = True
            # data = self.get(yf_query, params)
            data = jsonify_data(data)

        return data

    def load(self, file_name: str, data_type_class: Type[YahooFantasyObject] = None,
             new_data_dir: Union[Path, str, None] = None,
             all_output_as_json_str: bool = False) -> Union[str, YFO, List[YFO], Dict[str, YFO]]:
        """Load Yahoo Fantasy Sports data already stored locally.

        Note:
            This method will fail if the `save` method has not been called previously.

        Args:
            file_name (str): Name of file from which data will be loaded.
            data_type_class (Type[YahooFantasyObject], optional): YFPY models.py class for data casting.
            new_data_dir (str | Path, optional): Full path to new desired directory from which data will be loaded.
            all_output_as_json_str (bool): Boolean indicating if the output has been requested as a raw JSON string.

        Returns:
            object: Data loaded from the selected JSON file.

        """
        # change data load directory
        if new_data_dir:
            new_data_dir = new_data_dir if isinstance(new_data_dir, PosixPath) else Path(new_data_dir)
            self.update_data_dir(new_data_dir)

        # load selected data file
        saved_data_file_path = self.data_dir / f"{file_name}.json"
        if saved_data_file_path.exists():
            with open(saved_data_file_path, "r", encoding="utf-8") as data_file:
                unpacked = unpack_data(json.load(data_file), YahooFantasyObject)
                data = data_type_class(unpacked) if data_type_class else unpacked

                if isinstance(data, list):
                    # flatten list of single-key dictionaries with object values to list of object values if top level
                    # of loaded data is a list
                    data_element_key = list(data[0].keys())[0]
                    data = [el[data_element_key] for el in data]

            logger.debug(f"Data loaded locally from: {saved_data_file_path}")
        else:
            raise FileNotFoundError(f"File {saved_data_file_path} does not exist. Cannot load data locally without "
                                    f"having previously saved data.")

        if all_output_as_json_str:
            return jsonify_data(data)
        else:
            return data

    def retrieve(self, file_name: str, yf_query: Callable, params: Union[Dict[str, str], None] = None,
                 data_type_class: Type[YahooFantasyObject] = None,
                 new_data_dir: Union[Path, str, None] = None) -> Union[str, YFO, List[YFO], Dict[str, YFO]]:
        """Fetch data from the web or load it locally (combination of the save and load methods).

        Args:
            file_name (str): Name of file to/from which data will be saved/loaded.
            yf_query (Callable of YahooFantasySportsQuery): Chosen yfpy query method to run.
            params (dict of str: str, optional): Dictionary of parameters to be passed to chosen yfpy query function.
            data_type_class (Type[YahooFantasyObject], optional): YFPY models.py class for data casting.
            new_data_dir (str | Path, optional): Full path to new desired directory to/from which data will be
                saved/loaded.

        Returns:
            object: Data retrieved by the yfpy query OR loaded from the selected JSON file.

        """
        if self.dev_offline:
            return self.load(file_name, data_type_class, new_data_dir)
        else:
            if self.save_data:
                return self.save(file_name, yf_query, params, new_data_dir)
            else:
                return self.fetch(yf_query, params)

__init__

__init__(data_dir, save_data=False, dev_offline=False)

Instantiate data object to retrieve, save, and load Yahoo Fantasy Sports data.

Parameters:
  • data_dir (Path | str) –

    Directory path where data will be saved/loaded.

  • save_data (bool, default: False ) –

    Boolean determining whether data is saved after retrieval from the Yahoo FF API.

  • dev_offline (bool, default: False ) –

    Boolean for offline development (requires a prior online run with save_data = True).

Source code in yfpy/data.py
54
55
56
57
58
59
60
61
62
63
64
65
66
def __init__(self, data_dir: Union[Path, str], save_data: bool = False, dev_offline: bool = False):
    """Instantiate data object to retrieve, save, and load Yahoo Fantasy Sports data.

    Args:
        data_dir (Path | str): Directory path where data will be saved/loaded.
        save_data (bool, optional): Boolean determining whether data is saved after retrieval from the Yahoo FF API.
        dev_offline (bool, optional): Boolean for offline development (requires a prior online run with
            save_data = True).

    """
    self.data_dir: Path = data_dir if isinstance(data_dir, PosixPath) else Path(data_dir)
    self.save_data: bool = save_data
    self.dev_offline: bool = dev_offline

update_data_dir

update_data_dir(new_save_dir)

Modify the data storage directory if it needs to be updated.

Parameters:
  • new_save_dir (str | Path) –

    Full path to new desired directory where data will be saved/loaded.

Returns:
  • None

    None

Source code in yfpy/data.py
68
69
70
71
72
73
74
75
76
77
78
def update_data_dir(self, new_save_dir: Union[Path, str]) -> None:
    """Modify the data storage directory if it needs to be updated.

    Args:
        new_save_dir (str | Path): Full path to new desired directory where data will be saved/loaded.

    Returns:
        None

    """
    self.data_dir: Path = new_save_dir if isinstance(new_save_dir, PosixPath) else Path(new_save_dir)

fetch staticmethod

fetch(yf_query, params=None)

Run query to retrieve Yahoo Fantasy Sports data.

Parameters:
  • yf_query (Callable of YahooFantasySportsQuery) –

    Chosen yfpy query method to run.

  • params (dict of str, default: None ) –

    str, optional): Dictionary of parameters to be passed to chosen yfpy query function.

Returns:
  • object( Union[str, YFO, List[YFO], Dict[str, YFO]] ) –

    Data retrieved by the yfpy query.

Source code in yfpy/data.py
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
@staticmethod
def fetch(yf_query: Callable,
          params: Union[Dict[str, str], None] = None) -> Union[str, YFO, List[YFO], Dict[str, YFO]]:
    """Run query to retrieve Yahoo Fantasy Sports data.

    Args:
        yf_query (Callable of YahooFantasySportsQuery): Chosen yfpy query method to run.
        params (dict of str: str, optional): Dictionary of parameters to be passed to chosen yfpy query function.

    Returns:
        object: Data retrieved by the yfpy query.

    """
    if params:
        return yf_query(**params)
    else:
        return yf_query()

save

save(file_name, yf_query, params=None, new_data_dir=None)

Retrieve and save Yahoo Fantasy Sports data locally.

Parameters:
  • file_name (str) –

    Name of file to which data will be saved.

  • yf_query (Callable of YahooFantasySportsQuery) –

    Chosen yfpy query method to run.

  • params (dict of str, default: None ) –

    str, optional): Dictionary of parameters to be passed to chosen yfpy query function.

  • new_data_dir (str | Path, default: None ) –

    Full path to new desired directory to which data will be saved.

Returns:
  • object( Union[str, YFO, List[YFO], Dict[str, YFO]] ) –

    Data retrieved by the yfpy query.

Source code in yfpy/data.py
 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
def save(self, file_name: str, yf_query: Callable, params: Union[Dict[str, Any], None] = None,
         new_data_dir: Union[Path, str, None] = None) -> Union[str, YFO, List[YFO], Dict[str, YFO]]:
    """Retrieve and save Yahoo Fantasy Sports data locally.

    Args:
        file_name (str): Name of file to which data will be saved.
        yf_query (Callable of YahooFantasySportsQuery): Chosen yfpy query method to run.
        params (dict of str: str, optional): Dictionary of parameters to be passed to chosen yfpy query function.
        new_data_dir (str | Path, optional): Full path to new desired directory to which data will be saved.

    Returns:
        object: Data retrieved by the yfpy query.

    """
    # change data save directory
    if new_data_dir:
        new_data_dir = new_data_dir if isinstance(new_data_dir, PosixPath) else Path(new_data_dir)
        logger.debug(f"Data directory changed from {self.data_dir} to {new_data_dir}.")
        self.update_data_dir(new_data_dir)

    # create full directory path if any directories in it do not already exist
    if not self.data_dir.exists():
        self.data_dir.mkdir(parents=True, exist_ok=True)

    # check if parent YahooFantasySportsQuery.all_output_as_json_str = True, unset it for data saving, then reset it
    all_output_as_json = False
    # noinspection PyUnresolvedReferences
    if yf_query.__self__.all_output_as_json_str:
        if inspect.ismethod(yf_query):
            # noinspection PyUnresolvedReferences
            for cls in inspect.getmro(yf_query.__self__.__class__):
                if yf_query.__name__ in cls.__dict__:
                    # noinspection PyUnresolvedReferences
                    yf_query.__self__.all_output_as_json_str = False
                    all_output_as_json = True

    # run the actual yfpy query and retrieve the query results
    data = self.fetch(yf_query, params)

    # save the retrieved data locally
    saved_data_file_path = self.data_dir / f"{file_name}.json"
    with open(saved_data_file_path, "w", encoding="utf-8") as data_file:
        if isinstance(data, list):
            # unflatten list of object values to list of single-key dictionaries with object values if top level of
            # data to be saved is a list
            unnested_data = [{snakecase(el.__class__.__name__): el} for el in data]
        else:
            unnested_data = data

        jsonify_data_to_file(unnested_data, data_file)
    logger.debug(f"Data saved locally to: {saved_data_file_path}")

    # reset parent YahooFantasySportsQuery all_output_as_json_str = True and re-run query for json string return
    if all_output_as_json:
        # noinspection PyUnresolvedReferences
        yf_query.__self__.all_output_as_json_str = True
        # data = self.get(yf_query, params)
        data = jsonify_data(data)

    return data

load

load(
    file_name,
    data_type_class=None,
    new_data_dir=None,
    all_output_as_json_str=False,
)

Load Yahoo Fantasy Sports data already stored locally.

Note

This method will fail if the save method has not been called previously.

Parameters:
  • file_name (str) –

    Name of file from which data will be loaded.

  • data_type_class (Type[YahooFantasyObject], default: None ) –

    YFPY models.py class for data casting.

  • new_data_dir (str | Path, default: None ) –

    Full path to new desired directory from which data will be loaded.

  • all_output_as_json_str (bool, default: False ) –

    Boolean indicating if the output has been requested as a raw JSON string.

Returns:
  • object( Union[str, YFO, List[YFO], Dict[str, YFO]] ) –

    Data loaded from the selected JSON file.

Source code in yfpy/data.py
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
def load(self, file_name: str, data_type_class: Type[YahooFantasyObject] = None,
         new_data_dir: Union[Path, str, None] = None,
         all_output_as_json_str: bool = False) -> Union[str, YFO, List[YFO], Dict[str, YFO]]:
    """Load Yahoo Fantasy Sports data already stored locally.

    Note:
        This method will fail if the `save` method has not been called previously.

    Args:
        file_name (str): Name of file from which data will be loaded.
        data_type_class (Type[YahooFantasyObject], optional): YFPY models.py class for data casting.
        new_data_dir (str | Path, optional): Full path to new desired directory from which data will be loaded.
        all_output_as_json_str (bool): Boolean indicating if the output has been requested as a raw JSON string.

    Returns:
        object: Data loaded from the selected JSON file.

    """
    # change data load directory
    if new_data_dir:
        new_data_dir = new_data_dir if isinstance(new_data_dir, PosixPath) else Path(new_data_dir)
        self.update_data_dir(new_data_dir)

    # load selected data file
    saved_data_file_path = self.data_dir / f"{file_name}.json"
    if saved_data_file_path.exists():
        with open(saved_data_file_path, "r", encoding="utf-8") as data_file:
            unpacked = unpack_data(json.load(data_file), YahooFantasyObject)
            data = data_type_class(unpacked) if data_type_class else unpacked

            if isinstance(data, list):
                # flatten list of single-key dictionaries with object values to list of object values if top level
                # of loaded data is a list
                data_element_key = list(data[0].keys())[0]
                data = [el[data_element_key] for el in data]

        logger.debug(f"Data loaded locally from: {saved_data_file_path}")
    else:
        raise FileNotFoundError(f"File {saved_data_file_path} does not exist. Cannot load data locally without "
                                f"having previously saved data.")

    if all_output_as_json_str:
        return jsonify_data(data)
    else:
        return data

retrieve

retrieve(
    file_name,
    yf_query,
    params=None,
    data_type_class=None,
    new_data_dir=None,
)

Fetch data from the web or load it locally (combination of the save and load methods).

Parameters:
  • file_name (str) –

    Name of file to/from which data will be saved/loaded.

  • yf_query (Callable of YahooFantasySportsQuery) –

    Chosen yfpy query method to run.

  • params (dict of str, default: None ) –

    str, optional): Dictionary of parameters to be passed to chosen yfpy query function.

  • data_type_class (Type[YahooFantasyObject], default: None ) –

    YFPY models.py class for data casting.

  • new_data_dir (str | Path, default: None ) –

    Full path to new desired directory to/from which data will be saved/loaded.

Returns:
  • object( Union[str, YFO, List[YFO], Dict[str, YFO]] ) –

    Data retrieved by the yfpy query OR loaded from the selected JSON file.

Source code in yfpy/data.py
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
def retrieve(self, file_name: str, yf_query: Callable, params: Union[Dict[str, str], None] = None,
             data_type_class: Type[YahooFantasyObject] = None,
             new_data_dir: Union[Path, str, None] = None) -> Union[str, YFO, List[YFO], Dict[str, YFO]]:
    """Fetch data from the web or load it locally (combination of the save and load methods).

    Args:
        file_name (str): Name of file to/from which data will be saved/loaded.
        yf_query (Callable of YahooFantasySportsQuery): Chosen yfpy query method to run.
        params (dict of str: str, optional): Dictionary of parameters to be passed to chosen yfpy query function.
        data_type_class (Type[YahooFantasyObject], optional): YFPY models.py class for data casting.
        new_data_dir (str | Path, optional): Full path to new desired directory to/from which data will be
            saved/loaded.

    Returns:
        object: Data retrieved by the yfpy query OR loaded from the selected JSON file.

    """
    if self.dev_offline:
        return self.load(file_name, data_type_class, new_data_dir)
    else:
        if self.save_data:
            return self.save(file_name, yf_query, params, new_data_dir)
        else:
            return self.fetch(yf_query, params)