开发者

Default value for file path in function gives SyntaxError. Work around?

开发者 https://www.devze.com 2022-12-24 09:59 出处:网络
for this, import os.path def f(data_file_path=os.path.join(os.getcwd(),\'temp\'),type): ... return data I get this,

for this,

import os.path

def f(data_file_path=os.path.join(os.getcwd(),'temp'),type):
    ...
    return data

I get this,

SyntaxError: non-default argument follows default argument

Is there a way to make this work or do I have to define a variable such as,

rawda开发者_如何学Gota_path = os.path.join(os.getcwd(),'temp')

and then plug that into the function?


Move type before data_file_path

def f(type,data_file_path=os.path.join(os.getcwd(),'temp')):

Assigning values in the function parameter called default arguments, those should come afther non-default arguments


You have to switch the order of the arguments. Mandatory arguments (without default values) must come before arguments with set default values.


Rearrange the parameters:

def f(type, data_file_path=os.path.join(os.getcwd(),'temp')):
    pass

The reason for this is, that arguments with default values can be omitted.
But of you call f('foo'), it is not know if you want to set the type and omit data_file_path or not.


Arguments with a default value should be placed after all arguments without a default value.

Change it to:

import os.path

def f(type, data_file_path=os.path.join(os.getcwd(),'temp')):
    ...
    return data


Never mind.

SyntaxError: non-default argument follows default argument 

refers to the order of the arguments so,

def f(type,data_file_path=os.path.join(os.getcwd(),'temp')):

works!

me newbie

0

精彩评论

暂无评论...
验证码 换一张
取 消