0

I want to have the parameter for childDir to be optional.

def saveFile(parentDir, *childDir, fileName):
    # directory to store data
    DIR_PATH = Path(__file__).parent/parentDir/childDir/fileName
    # create dir_path if it does not exist
    Path(DIR_PATH).mkdir(parents=True, exist_ok=True)

    return DIR_PATH

saveFile("dirName", "dir", filename="test.py")

I'm getting an error

DIR_PATH = Path(file).parent/parentDir/childDir/fileName

TypeError: unsupported operand type(s) for /: 'WindowsPath' and 'tuple'

Shadow Walker
  • 979
  • 5
  • 27
  • 51
  • There is bit of confusion as to what asterisk does for parameter(s). Read https://stackoverflow.com/questions/36901/what-does-double-star-asterisk-and-star-asterisk-do-for-parameters If you want it to be optional make it keyword parameter. Also, at the moment `fileName` is mandatory keyword parameter. – buran Dec 20 '20 at 11:15

3 Answers3

1

You could do this:

def saveFile(parentDir, childDir=None, fileName=None):

i.e. make both childDir and fileName be optional, with defaults of None (or whatever makes more sense for default arguments).

Or change the order of the arguments, if you only want childDir to be optional:

def saveFile(parentDir, fileName, childDir=None):

Or you could do something like this:

def saveFile(parentDir, fileName, **kwargs):
   childDir = kwargs.get("childDir", None)

Which would let you have many optional keyword arguments.

I'd go for one of the first two options personally, unless you have good reasons not to.

Phil Gyford
  • 13,432
  • 14
  • 81
  • 143
  • Used the first suggestion but when i passed parantDir and filename excluding childName i.e ``saveFile("dirName", fileName="test.py")`` i got an error ``TypeError: unsupported operand type(s) for /: 'WindowsPath' and 'NoneType'``. Any ideas on how to solve this? – Shadow Walker Dec 20 '20 at 11:22
  • I found a work around, by using if statement. – Shadow Walker Dec 20 '20 at 11:25
  • Well, yes, if you don't pass a `childDir` then its value will be `None`. If that's no use to you you either need to change the default to be something other than `None` or to check within the function what its value is, and act appropriately. – Phil Gyford Dec 20 '20 at 11:36
1

If you change it to this:

def saveFile(parentDir, fileName, childDir=""):
   ...

saveFile("dirName", "test.py")
saveFile("dirName", "test.py", childDir="dir")

It will work with the rest of your code. It sets the default to an empty string so it still works with

DIR_PATH = Path(__file__).parent/parentDir/childDir/fileName
Lindert
  • 51
  • 2
1

childDir is a tuple and already optional because of the *.

You have to make it a string.

DIR_PATH = Path(__file__).parent / parentDir / '/'.join(childDir) / fileName
Nizam Mohamed
  • 8,751
  • 24
  • 32