1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] Passing Python slice syntax around to functions

Discussão em 'Python' iniciado por Stack, Setembro 17, 2025.

  1. Stack

    Stack Membro Participativo

    In Python, is it possible to encapsulate exactly the common slice syntax and pass it around? I know that I can use slice or __slice__ 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 __getitem__.

    For example, suppose I wrote a function to return some slice of a list.

    def get_important_values(some_list, some_condition, slice):
    elems = list(filter(some_condition, some_list))
    return elems[slice]


    This works fine if I manually pass in a slice object:

    In [233]: get_important_values([1,2,3,4], lambda x: (x%2) == 0, slice(0, None))
    Out[233]: [2, 4]


    But what I want to let the user pass is exactly the same slicing they would have used with __getitem__:

    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:) )


    Obviously this generates a syntax error. But is there any way to make this work, without writing my own mini parser for the x:y:t type slices, and forcing the user to pass them as strings?

    Motivation

    I could just make this example function return something directly sliceable, such as filter(some_condition, some_list), 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.

    Continue reading...

Compartilhe esta Página