Python Forum
passing an argument to avoid a global
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
passing an argument to avoid a global
#9
Something like this?
https://docs.python.org/3/library/operat...itemgetter

from functools import wraps


def int_itemgetter(index_or_key):
    """
    Is similar to operator.itemgetter, but it converts the element to an integer.
    """
    @wraps(int_itemgetter)
    def inner(element):
        return int(element[index_or_key])
    return inner

some_data = [(1,30,3), (4,20,6), (7,10,9)]
get_second = int_itemgetter(1)
print(sorted(some_data, key=get_second))
or written as class


class Itemgetter:
    def __init__(self, index_or_key):
        self._idx = index_or_key

    def __call__(self, element):
        return int(element[self._idx])

some_data = [(-1,30,3), (-4,20,6), (-7,10,9)]
get_first = Itemgetter(0)
print(sorted(some_data, key=get_first))
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
passing an argument to avoid a global - by Skaperen - Jul-11-2019, 06:21 AM
RE: passing an argument to avoid a global - by DeaD_EyE - Jul-12-2019, 01:19 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Passing Argument Errors cosmarchy 6 2,512 Sep-29-2021, 06:09 AM
Last Post: snippsat
  Passing argument from top-level function to embedded function JaneTan 2 2,302 Oct-15-2020, 03:50 PM
Last Post: deanhystad
  SyntaxError: positional argument follows keyword argument syd_jat 3 5,891 Mar-03-2020, 08:34 AM
Last Post: buran
  Passing an argument by reference Exsul 12 4,803 Aug-22-2019, 07:29 AM
Last Post: DeaD_EyE
  Global variable does not seem to be global. Columbo 6 3,770 Jul-15-2019, 11:00 PM
Last Post: Columbo
  help with threading module and passing global variables ricardons 1 7,925 Feb-21-2019, 12:48 PM
Last Post: stullis
  Is This Code Ok? How Can I Avoid Using Global Variables? digitalmatic7 9 5,906 Feb-15-2018, 09:32 AM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020