2

My question arise from two principles that I follow. Sometimes they get in conflict:

I often read that when importing from a module (like PyQt5 for example) I should only import what I actually need. Which makes a lot of sense, hence that is what I do.

Then I also read a lot on the benefits of namespaces and this also makes a lot of sense.

Here comes the problem I encounter:
Let's say I need to do import os because I need the module to do this: os.path.dirname(__file__) and this is the only thing I use "os" module for, I would be tempted to import this function only (from os.path import dirname).

If seems like a better import to me since I am only importing the function I actually need but then when I call dirname(__file__) later in my code I have completly lost the notion of namespace.

Is there a way to import only one part of a module while keeping the obligation to call it with the module name?
I know I can do something like from os.path import dirname as os_path_dirname. But this doesn't feel right...


Please note that this question has nothing to do with PyQt5 nor the os module, those are just examples that came to my mind, but this is more about the general concept of losing the notion of namespaces if I import only specific things.

My guess right now is that some modules (like "os") are very well written hence calling import os doesn't slow down the starting time of the program so it doesn't matter that we import the module has a whole, so people don't really care?

Is that correct? And if so, what happens to this very same problem with a module that is poorly written and that would actually slow down the program if imported has a whole?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Anto
  • 267
  • 1
  • 11
  • See [this answer](https://stackoverflow.com/a/21547583) in particular; performance-wise there is no difference, as the whole module is imported in either case. – mkrieger1 Jul 29 '22 at 10:19
  • Technically this matches your question more closely: https://stackoverflow.com/questions/15655224/performance-between-from-package-import-and-import-package, but the other question has the better answers. – mkrieger1 Jul 29 '22 at 10:21
  • @mkrieger1 Thanks for those links together they answer my question. So, since performance-wise it's the same and that I prefer being really explicit in my code I can always go with `import foo` and use `foo.bar()` every time i need to use a function from foo. This wouldn't be consider a bad practice, right ? – Anto Aug 01 '22 at 06:15
  • No, it would be considered good practice. – mkrieger1 Aug 01 '22 at 08:22

0 Answers0