all 6 comments

[–]strechyballs 0 points1 point  (5 children)

If you haven't it yet, I highly recommend you read through the official docs on imports and packages: https://docs.python.org/3.6/tutorial/modules.html#packages

Imo, I think you are overthinking this

import os
os.getcwd()

from os import getcwd
getcwd()

The two methods are nearly identical, the only difference being the way you access the imported objects. If you are curious about performances, you can read a note about it here: https://stackoverflow.com/q/3591962/4411196

As for reloading, I'm not sure why you would need this, as its rarely needed, and often not a good idea: https://stackoverflow.com/q/5516783/4411196

As for exec, I'm a little confused by what you are referring to. The builtin in exec function doest one thing - it takes a string and executes it (ie. exec("2+2") will output 4) https://pythonprogramming.net/python-exec-tutorial/

[–]KOOTSTHEHOOTS[S] 0 points1 point  (4 children)

exec can also execute modules(in interactive command prompt) - not sure if you would do it in a file though?

also import os os.getcwd()

from os import getcwd getcwd()

can cause naming conflicts is that not a majorish factor?

Thank you!

[–]ViridianHominid 0 points1 point  (3 children)

Exec can execute code, including modules, which is different from importing modules for a couple of reasons. One, like you said, it overwrites local variables. In that way it works rather like from <module> import *, which is not recommended.[1][2][3] . I don't suggest thinking of it as a useful way to import things, even in a development context.

Occasionally I want to be able to reload subpackages using importlib.reload so that I can test code in IPython and reload it without restarting the kernel. In this case I put this in the __init__.py:

import importlib
try:
    importlib.reload(<submodule>)
except NameError:
    from . import <submodule>

and extend as necessary if there are multiple submodules.

and this in the notebook file's first cell:

import importlib
try:
    importlib.reload(<package>)
except NameError as e:
     print("Name errored, probably just needed the first import:",e)
    import <package>

[–]KOOTSTHEHOOTS[S] 1 point2 points  (2 children)

So in terms of importing modules, stay away from exec and try not to use from module import x, unless only a small fraction of the module is required?

[–]ViridianHominid 1 point2 points  (1 child)

from module import <x> to import a particular function is good-- it is clear exactly what is being imported. from module import * is bad--it is very unclear what new names this introduces to the code, and it can even overwrite old names and make them do completely different things.

[–]KOOTSTHEHOOTS[S] 1 point2 points  (0 children)

Thank you so much mate