In the process of trying to validate a class property using "the canonical way to check for type in Python" I was trying to make a class with a bit of validation but where I'm trying to raise an error, instead the error is coming from the fact that the property isn't effectively being set. What am I doing wrong and how should I approach this.
# A class to represent a dataset upload replacement operation
import os
class DataReplacement:
def __init__(self, portal, inputfolder, input, output, audience):
self.portal = portal
self.inputfolder = inputfolder
self.input = input
self.output = output
self.audience = audience
self.fullpath = os.path.join(inputfolder, input)
@property
def fullpath(self):
return self._fullpath
@fullpath.setter
def fullpath(self, value):
try:
isinstance(self.inputfolder, str) and isinstance(self.input, str)
except ValueError:
raise ValueError("inputfolder and input must be a string") from None
fp = os.path.join(self.inputfolder, self.input)
if os.path.exists(fp):
self._fullpath = os.path.join(self.inputfolder, self.input)
else:
raise IOError(f"file {self.fullpath} does not exist.") from None
So for example if I set an instance to a file that actually exists, I get no error but in a second example if the file doesn't exist I get an error but it wasn't the one I wanted to get (if that makes sense?).
dr = DataReplacement('www.mywebsite.com', r'/Volumes/Project01/homedev/data', 'test_csv.csv', 'wa4r-1992', 'private')
The above works but 'ashdfiwuehv.csv' doesn't exist
dr2 = DataReplacement('www.mywebsite.com', r'/Volumes/Project01/homedev/data', 'ashdfiwuehv.csv', 'wa4r-1992', 'private')
I get ... AttributeError: 'DataReplacement' object has no attribute '_fullpath' instead of the IOError I was trying to raise.