zactrixo
zactrixo

Reputation: 71

Dictionary not identifying the right key

I'm trying to use a dictionary of file extensions to call the right method to convert a file but the dictionary keeps calling the first key instead of the correct one. Here is the dictionary:

def convertirV2(fichier):
    print(Path(fichier).suffix)
    choices = {
        ".docx": conver_docs(fichier),

        ".pdf": conver_pdf(fichier),

        ".txt": conver_txt(fichier),

        ".html": conver_html(fichier),

        ".xlsx" or ".xls": conver_xls(fichier),

        ".csv": conver_csv(fichier),

        is_binary(fichier): fichier

    }
    return choices.get(Path(fichier).suffix)

I can confirm that I'm giving the right key (.html in this case) but it still tries to call the conver_docs method. Any idea why that is?

Upvotes: 0

Views: 44

Answers (1)

Paul M.
Paul M.

Reputation: 10799

A simple example to illustrate the issue:

def foo():
    print("I'm in foo")

def bar():
    print("I'm in bar")

functions = {
    "a": foo(),
    "b": bar()
}

Output:

I'm in foo
I'm in bar
>>> 

As part of the dictionary's construction, you explicitly invoke the functions foo and bar, because of the (). You'll probably want key-value pairs of strings mapping to the functions themselves, rather than the values returned by those functions when called:

functions = {
    "a": foo,
    "b": bar
}

functions["a"]()

Output:

I'm in foo
>>> 

In my example, foo and bar take no parameters, but your conver_... functions do. To facilitate this, you would simply pass the parameter at the time at which you actually invoke the desired function:

choices = {
    ".docx": conver_docs,
    ".pdf": conver_pdf
    # ...
}

choices[Path(fichier).suffix](fichier)

In addition, ".xlsx" or ".xls": conver_xls(fichier) doesn't do what you think it does. The expression ".xlsx" or ".xls" will always evaluate to the single string ".xlsx", because in that expression the string-literal ".xlsx" is non-empty, which means it will be treated as a "truthy" value. An or expression only needs one of its operands to be True for the entire expression to be True, and so, due to short-circuit evaluation, the whole expression evaluates to ".xlsx". This means files with the extension ".xls" will not be considered by the dictionary. You'll have to make a separate key-value pair for ".xls".

Upvotes: 4

Related Questions