Note that there are some explanatory texts on larger screens.

plurals
  1. POPassing Python slice syntax around to functions
    text
    copied!<p>In Python, is it possible to encapsulate exactly the common slice syntax and pass it around? I know that I can use <code>slice</code> or <code>__slice__</code> to emulate slicing. But I want to pass the exact same syntax that I would put in the square brackets that would get used with <code>__getitem__</code>.</p> <p>For example, suppose I wrote a function to return some slice of a list.</p> <pre><code>def get_important_values(some_list, some_condition, slice): elems = filter(some_condition, some_list) return elems[slice] </code></pre> <p>This works fine if I manually pass in a slice object:</p> <pre><code>In [233]: get_important_values([1,2,3,4], lambda x: (x%2) == 0, slice(0, None)) Out[233]: [2, 4] </code></pre> <p>But what I want to let the user pass is <em>exactly</em> the same slicing they would have used with <code>__getitem__</code>:</p> <pre><code>get_important_values([1,2,3,4], lambda x: (x%2) == 0, (0:-1) ) # or get_important_values([1,2,3,4], lambda x: (x%2) == 0, (0:) ) </code></pre> <p>Obviously this generates a syntax error. But is there any way to make this work, without writing my own mini parser for the <code>x:y:t</code> type slices, and forcing the user to pass them as strings?</p> <p><strong>Motivation</strong></p> <p>I could just make this example function return something directly sliceable, such as <code>filter(some_condition, some_list)</code>, which will be the whole result as a list. In my actual example, however, the internal function is much more complicated, and if I know the slice that the user wants ahead of time, I can greatly simplify the calculation. But I want the user to not have to do much extra to tell me the slice ahead of time.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload