Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IndexError: tuple index out of range when parsing method arguments

I've already checked this question, but couldn't find an answer there. Here is a simple example that demonstrates my use case:

def log(*args):
    message = str(args[0])
    arguments = tuple(args[1:])
    # message itself
    print(message)
    # arguments for str.format()0
    print(arguments)
    # shows that arguments have correct indexes
    for index, value in enumerate(arguments):
        print("{}: {}".format(index, value))
    # and amount of placeholders == amount of arguments
    print("Amount of placeholders: {}, Amount of variables: {}".format(message.count('{}'), len(arguments)))

    # But this still fails! Why?
    print(message.format(arguments))

log("First: {}, Second: {}, Third: {}, Fourth: {}", "asdasd", "ddsdd", "12312333", "fdfdf")

And the output:

First: {}, Second: {}, Third: {}, Fourth: {}
('asdasd', 'ddsdd', '12312333', 'fdfdf')
0: asdasd
1: ddsdd
2: 12312333
3: fdfdf
Amount of placeholders: 4, Amount of variables: 4
Traceback (most recent call last):
  File "C:/Users/sbt-anikeev-ae/IdeaProjects/test-this-thing-on-python/test-this-thing.py", line 12, in <module>
    log("First: {}, Second: {}, Third: {}, Fourth: {}", "asdasd", "ddsdd", "12312333", "fdfdf")
  File "C:/Users/sbt-anikeev-ae/IdeaProjects/test-this-thing-on-python/test-this-thing.py", line 10, in log
    print(message.format(arguments))
IndexError: tuple index out of range

P.S: I've already refused using such a method (that wraps str.format()), as it seems to be excess. But still it puzzles me, why wouldn't this work as expected?

like image 925
Alexander Avatar asked Jan 13 '17 10:01

Alexander


People also ask

How do I fix IndexError tuple index out of range?

The IndexError: Python tuple index out of range error occurs when you try to access an item in a tuple that does not exist. To solve this problem, make sure that whenever you access an item from a tuple that the item for which you are looking exists.

What does the index out of range error mean in case list or tuple?

You'll get the Indexerror: list index out of range error when you try and access an item using a value that is out of the index range of the list and does not exist. This is quite common when you try to access the last item of a list, or the first one if you're using negative indexing.

How do you find the index of a tuple?

Python Tuple index() MethodPython index() method searches for the given element in a tuple and returns its position. It returns first occurrence of the element in the tuple. Index starts from 0 and end at n-1 where n is length of tuple.

What is a tuple index?

Tuple indices are used to optimize searches that have 0 or more medial-search strings and 0 or 1 final-search strings. They can also be used to optimize searches for an initial search string if no ordinary index is available over that attribute.


2 Answers

you have to use * to unpack the tuple into actual arguments for format:

print(message.format(*arguments))

otherwise, arguments is seen as the sole argument of format (and it works for the first {} occurrence, by converting your tuple to string, but chokes when it encounters the second occurrence of {})

like image 132
Jean-François Fabre Avatar answered Oct 29 '22 12:10

Jean-François Fabre


You need to pass arguments not tuple. This is done by using '*arguments'. Expanding tuples into arguments

def log(*args):
    message = str(args[0])
    arguments = tuple(args[1:])
    # message itself
    print(message)
    # arguments for str.format()0
    print(arguments)
    # shows that arguments have correct indexes
    for index, value in enumerate(arguments):
        print("{}: {}".format(index, value))
    # and amount of placeholders == amount of arguments
    print("Amount of placeholders: {}, Amount of variables: {}".format(message.count('{}'), len(arguments)))

    # But this still fails! Why?
    print(type(arguments))
    print(message.format(*arguments))

log("First: {}, Second: {}, Third: {}, Fourth: {}", "asdasd", "ddsdd", "12312333", "fdfdf")  
like image 32
ppasler Avatar answered Oct 29 '22 13:10

ppasler