I have a situation where I would like to conditionally slice a string from the reported position of an '@' symbol; the condition being: slice the string if the '@' is there, else leave it untouched. I thought up two ways, one using a function, the other using an inline conditional expression. Which method is the most Pythonic?
Using a function
>>> def slice_from_at(inp):
... res = inp.find('@')
... if res == -1:
... return None
... else:
... return res
>>> c = 'agent_address@agent_address'
>>> c[:slice_from_at(c)]
... 'agent_address'
Using an inline conditional expression
>>> c = 'agent_address@agent_address'
>>> c[:None if c.find('@') == -1 else c.find('@')]
... 'agent_address'
Although using the inline conditional expression is more terse and, some may argue more economical - is the function method is more Pythonic because it more readable?
Not only is a function more readable, it is also reusable.
The inline expression may call c.find('@')
twice, which is inefficient.
As Useless has mentioned in the comments, there are already built in functions to do this; you really don't need to define your own function in this case:
agent,_,address = c.partition('@')
By the way, a callback is a function that is passed in as an argument and called later. You don't have a callback since it is not being called later. I think it should just be called a function.