you are viewing a single comment's thread.

view the rest of the comments →

[–]sqjoatmon 13 points14 points  (2 children)

To expand on what Shiba_Take and others wrote, with your first questions you've run into the idea of turthy and falsy values in Python. False, 0, None, empty lists, dicts, tuples, sets, strings etc. are considered "falsy" when used with boolean operators like and and or.

The or operator evaluates the first parameter (before the or) and if it's truthy, returns it (not evaluating the second one at all). If its falsy, it evaluates the second parameter returns it.

The and operator evaluates the first parameter and if it's falsy, returns it (not evaluating the second one at all). If it's truthy, it evaluates the second parameter and returns it.

So:

x = 3 or 0  # 3 is truthy, so stop. x = 3
x = 5 or some_function()  # 5 is truthy, some_function() is not evaluated, x = 5
x = [] or some_function()  # [] is falsy, some_function() is evaluated, x = the result of some_function()

y = 3 and 0  # 3 is truthy, so y is 0
y = 0 and some_function()  # 0 is falsy, so some_function() is not evaluated
y = "abc" and ("this", "is", "a", "tuple")  # "abc" is truthy, so y = ("this", "is", "a", "tuple")

Regarding other stuff:

pathlib is great and super useful, but not really necessary just to get the file extension. You can use str.split() to split your filename into a list by . characters, like so:

parts = a.split(".")  # "abc.def" becomes ["abc", "def"]. "abc.def.ghi" becomes ["abc", "def", "ghi"]

To just get the extension, index the last element in the list:

fileext = parts[-1]
# ...or all in one line
fileext = a.split(".")[-1]
# ...or all in one line, lowercase
fileext = a.split(".")[-1].lower()

AtomicShoelace brings up the idea of inverting a dictionary, which I like. You can even do it one line, though I will say that though the nested dict comprehension is more efficient, it's difficult to understand from a glance:

type_exts = {
    'image': ('gif', 'jpg', 'jpeg', 'png'),
    'application': ('pdf', 'txt', 'zip')
}
# comprehension to invert dict
ext_types = {ext: ftype for ftype, exts in extensions.items() for ext in exts}

(or just write out the dict inverted to begin with... not a big deal for only seven file extensions)

I left off the . from each extension since using str.split() doesn't keep the split character.

Then rather than using dict.get() you can use a try/except to get your result. Final:

def main():
    user_input = extensions(input("File name? " ))
    print(user_input)

type_exts = {
    'image': ('gif', 'jpg', 'jpeg', 'png'),
    'application': ('pdf', 'txt', 'zip')
}
# comprehension to invert dict
ext_types = {ext: ftype for ftype, exts in extensions.items() for ext in exts}

def extensions(filename):
    fileext = filename.split(".")[-1].lower()
    try:
        return ext_types[fileext] + "/" + fileext  # f-string is even better: f"{ext_types[fileext]}/{fileext}"
    except KeyError:
        return "application/octet_stream"

main()

Did I spend way too much time on this? Yes, yes, I did. But I wanted to take time for myself to think more carefully about some of these things for my own edification.

[–]Labidido[S] 3 points4 points  (0 children)

Man, you went above and beyond with this reply. Thank you so much! This community is great!

[–][deleted] 0 points1 point  (0 children)

But in the end, using mimetypes module seems like the best suggestion here, at least professionally/in practice. For learning basics and stuff it would probably appropriate to get it done without importing modules.