Path: blob/master/ invest-robot-contest_TinkoffBotTwitch-main/venv/lib/python3.8/site-packages/pandas/io/pickle.py
7826 views
""" pickle compat """1from __future__ import annotations23import pickle4from typing import Any5import warnings67from pandas._typing import (8CompressionOptions,9FilePath,10ReadPickleBuffer,11StorageOptions,12WriteBuffer,13)14from pandas.compat import pickle_compat as pc15from pandas.util._decorators import doc1617from pandas.core.shared_docs import _shared_docs1819from pandas.io.common import get_handle202122@doc(23storage_options=_shared_docs["storage_options"],24compression_options=_shared_docs["compression_options"] % "filepath_or_buffer",25)26def to_pickle(27obj: Any,28filepath_or_buffer: FilePath | WriteBuffer[bytes],29compression: CompressionOptions = "infer",30protocol: int = pickle.HIGHEST_PROTOCOL,31storage_options: StorageOptions = None,32) -> None:33"""34Pickle (serialize) object to file.3536Parameters37----------38obj : any object39Any python object.40filepath_or_buffer : str, path object, or file-like object41String, path object (implementing ``os.PathLike[str]``), or file-like42object implementing a binary ``write()`` function.4344.. versionchanged:: 1.0.045Accept URL. URL has to be of S3 or GCS.46{compression_options}4748.. versionchanged:: 1.4.0 Zstandard support.4950protocol : int51Int which indicates which protocol should be used by the pickler,52default HIGHEST_PROTOCOL (see [1], paragraph 12.1.2). The possible53values for this parameter depend on the version of Python. For Python542.x, possible values are 0, 1, 2. For Python>=3.0, 3 is a valid value.55For Python >= 3.4, 4 is a valid value. A negative value for the56protocol parameter is equivalent to setting its value to57HIGHEST_PROTOCOL.5859{storage_options}6061.. versionadded:: 1.2.06263.. [1] https://docs.python.org/3/library/pickle.html6465See Also66--------67read_pickle : Load pickled pandas object (or any object) from file.68DataFrame.to_hdf : Write DataFrame to an HDF5 file.69DataFrame.to_sql : Write DataFrame to a SQL database.70DataFrame.to_parquet : Write a DataFrame to the binary parquet format.7172Examples73--------74>>> original_df = pd.DataFrame({{"foo": range(5), "bar": range(5, 10)}}) # doctest: +SKIP75>>> original_df # doctest: +SKIP76foo bar770 0 5781 1 6792 2 7803 3 8814 4 982>>> pd.to_pickle(original_df, "./dummy.pkl") # doctest: +SKIP8384>>> unpickled_df = pd.read_pickle("./dummy.pkl") # doctest: +SKIP85>>> unpickled_df # doctest: +SKIP86foo bar870 0 5881 1 6892 2 7903 3 8914 4 992""" # noqa: E50193if protocol < 0:94protocol = pickle.HIGHEST_PROTOCOL9596with get_handle(97filepath_or_buffer,98"wb",99compression=compression,100is_text=False,101storage_options=storage_options,102) as handles:103if handles.compression["method"] in ("bz2", "xz") and protocol >= 5:104# some weird TypeError GH#39002 with pickle 5: fallback to letting105# pickle create the entire object and then write it to the buffer.106# "zip" would also be here if pandas.io.common._BytesZipFile107# wouldn't buffer write calls108handles.handle.write(pickle.dumps(obj, protocol=protocol))109else:110# letting pickle write directly to the buffer is more memory-efficient111pickle.dump(obj, handles.handle, protocol=protocol)112113114@doc(115storage_options=_shared_docs["storage_options"],116decompression_options=_shared_docs["decompression_options"] % "filepath_or_buffer",117)118def read_pickle(119filepath_or_buffer: FilePath | ReadPickleBuffer,120compression: CompressionOptions = "infer",121storage_options: StorageOptions = None,122):123"""124Load pickled pandas object (or any object) from file.125126.. warning::127128Loading pickled data received from untrusted sources can be129unsafe. See `here <https://docs.python.org/3/library/pickle.html>`__.130131Parameters132----------133filepath_or_buffer : str, path object, or file-like object134String, path object (implementing ``os.PathLike[str]``), or file-like135object implementing a binary ``readlines()`` function.136137.. versionchanged:: 1.0.0138Accept URL. URL is not limited to S3 and GCS.139140{decompression_options}141142.. versionchanged:: 1.4.0 Zstandard support.143144{storage_options}145146.. versionadded:: 1.2.0147148Returns149-------150unpickled : same type as object stored in file151152See Also153--------154DataFrame.to_pickle : Pickle (serialize) DataFrame object to file.155Series.to_pickle : Pickle (serialize) Series object to file.156read_hdf : Read HDF5 file into a DataFrame.157read_sql : Read SQL query or database table into a DataFrame.158read_parquet : Load a parquet object, returning a DataFrame.159160Notes161-----162read_pickle is only guaranteed to be backwards compatible to pandas 0.20.3.163164Examples165--------166>>> original_df = pd.DataFrame({{"foo": range(5), "bar": range(5, 10)}}) # doctest: +SKIP167>>> original_df # doctest: +SKIP168foo bar1690 0 51701 1 61712 2 71723 3 81734 4 9174>>> pd.to_pickle(original_df, "./dummy.pkl") # doctest: +SKIP175176>>> unpickled_df = pd.read_pickle("./dummy.pkl") # doctest: +SKIP177>>> unpickled_df # doctest: +SKIP178foo bar1790 0 51801 1 61812 2 71823 3 81834 4 9184""" # noqa: E501185excs_to_catch = (AttributeError, ImportError, ModuleNotFoundError, TypeError)186with get_handle(187filepath_or_buffer,188"rb",189compression=compression,190is_text=False,191storage_options=storage_options,192) as handles:193194# 1) try standard library Pickle195# 2) try pickle_compat (older pandas version) to handle subclass changes196# 3) try pickle_compat with latin-1 encoding upon a UnicodeDecodeError197198try:199# TypeError for Cython complaints about object.__new__ vs Tick.__new__200try:201with warnings.catch_warnings(record=True):202# We want to silence any warnings about, e.g. moved modules.203warnings.simplefilter("ignore", Warning)204return pickle.load(handles.handle)205except excs_to_catch:206# e.g.207# "No module named 'pandas.core.sparse.series'"208# "Can't get attribute '__nat_unpickle' on <module 'pandas._libs.tslib"209return pc.load(handles.handle, encoding=None)210except UnicodeDecodeError:211# e.g. can occur for files written in py27; see GH#28645 and GH#31988212return pc.load(handles.handle, encoding="latin-1")213214215