On Tue, Aug 2, 2016 at 1:31 AM, Ganesh Pal <ganesh1...@gmail.com> wrote: > I am a Linux user on python 2,6 . I have a very simple question > > I was going the zen of python by Tim peters and found an example that > demonstrates Explicit is better than implicit > > """Load the cat, dog, and mouse models so we can edit instances of them.""" > def load(): > from menagerie.cat.models import * > from menagerie.dog.models import * > from menagerie.mouse.models import * > #----------------------------------------------------------------------- > def load(): > from menagerie.models import cat as cat_models > from menagerie.models import dog as dog_models > from menagerie.models import mouse as mouse_models > #----------------------------------------------------------------------- > print 'Explicit is better than implicit.' > > > I had a question on the above example > > 1. I haven't used " from menagerie.cat.models import * is it a good > programming practice to use import * ? if answer is "NO " then are > there situation where you are forced to use import * >
Specifically to that example? No it's never a good idea to do a star-import inside a function. It's completely illegal in Python 3. Normally, you'll want to do your imports at module level, and not with the star. There are a very few places where a star import is the best thing to do, and they're usually because of a tight binding between the two modules. For example, it's common for __init__.py to say "from .something import *", to make a package's module's contents available in the package itself. Also, a Python module with a C accelerator will often start or end by star-importing from the accelerator (eg ast.py "from _ast import *"). If you're not doing something like that, there are only a handful of modules that are really designed with star-imports in mind (eg tkinter, stat), and even then, I personally don't recommend it. The downside of a star-import is that it breaks the common pattern that the first use of a name is its definition. If you see, somewhere in a program, "conn = psycopg2.connect(...)", you can go up to the top of the program to find "import psycopg2" and know that it's a module - even if you don't recognize the name (since it's a third-party one), you can know that it's a module. Similarly, if you see "conn = connect(...)", you can go up to the top - but then it depends on whether the program author wrote "from psycopg2 import connect" or "from psycopg2 import *". In the latter case, you have to *guess* that the name "connect" might have come from there. So, my recommendation is: Use "import *" only when you control both ends of something. Otherwise, be explicit. ChrisA -- https://mail.python.org/mailman/listinfo/python-list