What is the need of defining the argument variable inside the function?
def load_housing_data(housing_path=HOUSING_PATH):
csv_path = os.path.join(housing_path, "housing.csv")
return pd.read_csv(csv_path)
Can't we simply ignore it like -
def load_housing_data():
csv_path = os.path.join(HOUSING_PATH, "housing.csv")
return pd.read_csv(csv_path)
I'm believe -
def load_housing_data():
is more right than -
def load_housing_data(housing_path=HOUSING_PATH):
CodePudding user response:
def load_housing_data(housing_path=HOUSING_PATH):
argument housing_path have HOUSING_PATH as default value, that means, if you call function load_housing_data()
and no passed that argument, by default taken HOUSING_PATH as value
CodePudding user response:
Both ways will work.
In the first one you are defaulting the argument to a value. This allows you to skip supplying one if the default value is sufficient, but still allows you to supply an alternate if it is not sufficient.
def load_housing_data(housing_path=HOUSING_PATH):
csv_path = os.path.join(housing_path, "housing.csv")
return pd.read_csv(csv_path)
#you can do this
data = load_housing_data()
#or this
data = load_housing_data(SOME_OTHER_PATH)
In the second you are statically supplying the value and removing your ability to supply an alternate one.
def load_housing_data():
csv_path = os.path.join(HOUSING_PATH, "housing.csv")
return pd.read_csv(csv_path)
#only option
data = load_housing_data()
However, if you are going to use the second version, then you might as well make csv_path
global. You've made it so csv_path
will never be different so, no reason to keep remaking it every time you call the def
.
CSV_PATH = os.path.join(HOUSING_PATH, "housing.csv")
def load_housing_data():
return pd.read_csv(CSV_PATH)
Once you do that, the def
is essentially just an alias so, you don't need it.
CSV_PATH = os.path.join(HOUSING_PATH, "housing.csv")
data = pd.read_csv(CSV_PATH)