From 732070b0d2b7365ec2aea25e36e98b4035c87c2e Mon Sep 17 00:00:00 2001 From: Bryan Weber Date: Thu, 15 Dec 2022 16:35:55 -0500 Subject: [PATCH] Move _handle attribute up in CloudPath __init__ (#300) * Move _handle attribute up in CloudPath __init__ The _handle attribute needs to be set before any code can raise an exception. This is because if something tries to call __del__ after the exception as the process is exiting, _handle must be set to avoid an AttributeError in __del__. Resolves #299. * Formatting Co-authored-by: Bryan Weber --- cloudpathlib/cloudpath.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/cloudpathlib/cloudpath.py b/cloudpathlib/cloudpath.py index 91e7c932..e808f5e4 100644 --- a/cloudpathlib/cloudpath.py +++ b/cloudpathlib/cloudpath.py @@ -166,6 +166,11 @@ class CloudPath(metaclass=CloudPathMeta): cloud_prefix: str def __init__(self, cloud_path: Union[str, "CloudPath"], client: Optional["Client"] = None): + + # handle if local file gets opened. must be set at the top of the method in case any code + # below raises an exception, this prevents __del__ from raising an AttributeError + self._handle = None + self.is_valid_cloudpath(cloud_path, raise_on_error=True) # versions of the raw string that provide useful methods @@ -190,9 +195,6 @@ def __init__(self, cloud_path: Union[str, "CloudPath"], client: Optional["Client # track if local has been written to, if so it may need to be uploaded self._dirty = False - # handle if local file gets opened - self._handle = None - def __del__(self): # make sure that file handle to local path is closed if self._handle is not None: