Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In line Conditional Expression or Function - Pythonic?

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?

like image 707
Raz Avatar asked Dec 09 '25 18:12

Raz


2 Answers

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.

like image 103
unutbu Avatar answered Dec 12 '25 08:12

unutbu


Most Pythonic?

Don't reinvent the wheel, use str.partition()

def slice_from_at(inp):
    if '@' in inp:
        return inp.partition('@')[2]
    return inp

If you're more concerned about speed than readability, try str.rsplit():

def slice_from_at(inp):
    return inp.rsplit('@', 1)[-1]

Neither of your examples includes a "callback". Nor should they.

A well-named function that does one thing and does that one thing well is about as Pythonic as it gets. If it's backed-up with unit tests, so much the better.

like image 24
Johnsyweb Avatar answered Dec 12 '25 07:12

Johnsyweb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!