I'm trying to simplify some of my code and am wondering which values when passed as a parameter to a function cause that parameter to default to it set value (as defined in the def
statement). Example:
In one of my classes I have the following function
def scrape(self, search_term='animals'):
What value(s) other than no value at all can be passed to the scrape
function that will cause the function to use it's default value (animals)?
In the following function in my main class I call the function with a variable that is by default set to None
, which I was thinking would cause scrape
to use animals
, but it actually sets search_term=None
def list_channels(query=None):
live_source = exploreorg.Site()
links = live_source.scrape(query)
Is there some value I can pass to the scrape
function that will enable this behavior or is my only option to do an if/else?
def list_channels(query=None):
live_source = exploreorg.Site()
if query is None:
links = live_source.scrape()
else:
links = live_source.scrape(query)
I feel like that is so bulky, but if it's the best way, then I'm ok with it. I imagine there is a better way to accomplish what I'm trying to do.
Python uses the default value only when no value is passed. To avoid repeating the value, maybe you can use None
as the default value?
def scrape(self, search_term=None):
search_term = search_term or 'animals'
def list_channels(query=None):
live_source = exploreorg.Site()
links = live_source.scrape(query)
Or reuse a variable?
DEFAULT_SEARCH_TERM = 'animals'
def scrape(self, search_term=DEFAULT_SEARCH_TERM):
...
def list_channels(query=DEFAULT_SEARCH_TERM):
live_source = exploreorg.Site()
links = live_source.scrape(query)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With