30 ms·
My big problem when reading Python code are "from" and "as" in imports. To illustrate: I read a function doing a few calls in file, and I want to understand wh
by t0mk 11y ago
My big problem when reading Python code are "from" and "as" in imports.
To illustrate: I read a function doing a few calls in file, and I want to understand what happens in one of the calls (a name without any dot prefix). So I do forward search for the name in the current file (a bit silly when thinking of it, but forward slash is so close to my index finger; and in web browser the search is forward by default), and it only finds it in imports in the beginning of the file after "from". At this point I lose the context of the function I was originally reading, because I have seen other chunks of code which I try to understand a bit. Also I lose the position of the original function in the file. If I want to dive deeper to the calls, I look up the module in question.
If the name would be use with full namespace prefix, like
import datetime
datetime.datetime.utcnow()
^ I could immediately see which module it's coming from and go there. Straight up! I wouldn't need finger acrobatics, and it would be readable in e.g. github code viewer.
If you are really bothered by the length of the dot-prefixed names, why not do
now = datetime.datetime.utcnow()
print(now())
^ That's all clear, and most likely you will fit to 79 chars per line.
Namespaces are a good idea, and explicit over implicit, right? I understand that there are some conventions (like _ for gettext), but I see importing names without dot prefixes as killing readability.
- vadskye 11y agoMinor nitpick: I think you mean now = datetime.datetime.utcnow # no parentheses More generally, I think the strongest argument for using "from" is when you're dealing with redundant "foo.foo.bar" names. Would you really be confused at seeing "datetime.utcnow()" instead of "datetime.datetime.utcnow()"?
- majika 11y agoTo me, this sounds like a failure of your tooling rather than the code you're reading. Vim with Jedi, PyCharm and PyDev can all jump straight to definitions. What's your development environment? I'll use `from <module> import <identifiers>` when the identifiers' names express their purpose, and aren't dependent on the module's name. Importing identifiers directly makes the code using them less noisy [0], and makes it possible to replace the source module for the identifiers later on. In Django projects, I'll often need to rename modules or move identifiers between modules, and so using `from` imports makes that a lot easier. I agree that `as` imports should be used sparingly. [0]: your suggested solution is even more noisy than using the qualified name, because now you have a variable hanging around and readers have to work out if `now` is going to be reassigned or used later.