Hi.
I have a "style" question: Sometimes, modules will only be used in a
particular, optional, part of a program (function, class), that will not
always be used when the application is run. So I think it is better to
import them only there, not on the top of the file (together with the
other imports). Is that okay, or are there good reasons for not doing so?
Regards
Andreas 7 1533
Andreas Neudecker wrote: I have a "style" question: Sometimes, modules will only be used in a particular, optional, part of a program (function, class), that will not always be used when the application is run. So I think it is better to import them only there, not on the top of the file (together with the other imports). Is that okay, or are there good reasons for not doing so?
There are not *strong* reasons for avoiding the delayed-import style,
although clearly maintainability can be affected. It makes it somewhat
harder for a maintainer to see that a given module is used at all.
I would not bother putting imports that are rarely used in only the
functions which need them *unless* I had a really large module which
took a long time to import and I was actually having problems with
startup time for the application.
Basically doing this is an optimization, and you shouldn't be optimizing
before the program is working, and you shouldn't be optimizing without
a real need for it. (That is, just because it's a little faster doesn't
mean it's worth doing.)
-Peter
Andreas Neudecker wrote: Hi.
I have a "style" question: Sometimes, modules will only be used in a particular, optional, part of a program (function, class), that will not always be used when the application is run. So I think it is better to import them only there, not on the top of the file (together with the other imports). Is that okay, or are there good reasons for not doing so?
That's perfectly ok, if you want/need to optimize your program startup
time. It might also save a byte or two of memory, depending on how large
the module is.
-- Gerhard
Peter Hansen <pe***@engcorp. com> wrote:
.... Basically doing this is an optimization, and you shouldn't be optimizing before the program is working, and you shouldn't be optimizing without a real need for it. (That is, just because it's a little faster doesn't mean it's worth doing.)
Aside from being an optimization, it's also good for documentation.
If you see an import at the top of a file it might not be immediately
clear how or why the module is being used. It's similar reasoning to
why you might define variables in the narrowest scope posible.
"JCM" <jo************ ******@myway.co m> wrote in message
news:bl******** **@fred.mathwor ks.com... Peter Hansen <pe***@engcorp. com> wrote: ...
Basically doing this is an optimization, and you shouldn't be optimizing before the program is working, and you shouldn't be optimizing without a real need for it. (That is, just because it's a little faster doesn't mean it's worth doing.)
Aside from being an optimization, it's also good for documentation. If you see an import at the top of a file it might not be immediately clear how or why the module is being used. It's similar reasoning to why you might define variables in the narrowest scope posible.
There are also reasons having to do with circular imports that
you might not want to import at the top. However, this situation
is hazardous enough that some effort in removing the circularity
is usually warranted.
In general, I agree with the style guide: put them at the top
of the module unless there is a real, strong reason to put
them somewhere else. Even then, I'd put a comment in
with the main imports pointing out where the embedded
import exists.
John Roth
JCM wrote: Peter Hansen <pe***@engcorp. com> wrote: ...
Basically doing this is an optimization, and you shouldn't be optimizing before the program is working, and you shouldn't be optimizing without a real need for it. (That is, just because it's a little faster doesn't mean it's worth doing.)
Aside from being an optimization, it's also good for documentation. If you see an import at the top of a file it might not be immediately clear how or why the module is being used. It's similar reasoning to why you might define variables in the narrowest scope posible.
I'm not sure it's necessarily any clearer when you put the import
somewhere down in the file, effectively hiding it from casual viewing.
At the top, it's at least clear that the module *is* imported. If
you care how it's used, a simple search for "module." will show all
the places where it's used.
In the middle of code somewhere, you can clearly see how it's being
used only if you're actually looking at that exact line.
John Roth has the right approach: whatever you do, a comment up
at the top with the others would go a long way towards appeasing
any concerns about maintainability . Unfortunately, that does mean
there's isolated duplication (the import, somewhere below, plus the
comment at the top) and therefore another, though perhaps lesser,
maintainability problem.
-Peter
Hi.
Thank you for your opinions!
Good to look at it from different sides.
So I think one could sum it all up as:
- Best place for importing modules is at the top of the file.
- if optimisation requires or programmer desires to import specific
modules somewhere else, it is a good idea to add a comment at the top,
where all the other modules are imported.
- for optimasation importing inside modules/functions will only make
sense if loading the module takes time (try rpy, the wrapper for R!) and
is not used every time the program runs.
I liked Peter Hansen's remark on optimasation:
"Basically doing this is an optimization, and you shouldn't be
optimizing before the program is working, and you shouldn't be
optimizing without a real need for it. (That is, just because it's a
little faster doesn't mean it's worth doing.)"
But also the contrary remark by "JCM":
"Aside from being an optimization, it's also good for documentation.
If you see an import at the top of a file it might not be immediately
clear how or why the module is being used. It's similar reasoning to
why you might define variables in the narrowest scope posible."
Thanks everybody.
Regards
Andreas
Mel Wilson wrote: In article <3F************ ***@engcorp.com >, Peter Hansen <pe***@engcorp. com> wrote:I would not bother putting imports that are rarely used in only the functions which need them *unless* I had a really large module which took a long time to import and I was actually having problems with startup time for the application.
I can see a case for
if __name__ == '__main__': import getopt ...
and even sys (for sys.argv), if the rest of the module doesn't deal with sys. But that's because running as the main module instead of a library module is a big change in operating environment and rationale.
Agreed! This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Fritz Bosch |
last post by:
Hi experts
Is is possible to import/manipulate a module such that
I can supply its __dict__?
I want to supply my own dict subclass object to be filled
by the import, e.g. a class like:
>>> class MyModuleDict(dict):
.... def __setitem__(self,name,val):
|
by: Torsten Mohr |
last post by:
Hi,
i tried to find the file and line in the C sources of python
where the command "import" is implemented. Can anybody give
me some hint on this?
Thanks,
Torsten.
|
by: Steve Holden |
last post by:
This is even stranger: it makes it if I import the module a second time:
import dbimp as dbimp
import sys
if __name__ == "__main__":
dbimp.install()
#k = sys.modules.keys()
#k.sort()
#for kk in k:
|
by: Nicolas Fleury |
last post by:
Hi,
I'm trying to support two Python versions at the same time and I'm
trying to find effective mechanisms to support modules compiled in C++
transparently.
All my code in under a single package. Is it possible to override the
import mechanism only for modules under that package and sub-packages so
that?:
import cppmymodule
|
by: passion_to_be_free |
last post by:
Okay, so in my li'l python script I'm importing a few 3rd party modules
that I have installed on my comp. I need to distribute this script to
several other people, but I won't have access to install the modules on
their comp's. I'm thinking I'll include these modules with my script
and deliver them as a bundle. When I write my script, is there a way to
declare the import statements and specify a relative path to where the
modules are...
| |
by: fortepianissimo |
last post by:
Say I have the following package organization in a system I'm
developing:
A
|----B
|----C
|----D
I have a module, say 'foo', that both package D and B require. What is
the best practice in terms of creating a 'common' package that hosts
|
by: praveenkumar.117 |
last post by:
Hi All,
What is the difference between
import string
and
from string import *
Regards,
Praveen
|
by: Connelly Barnes |
last post by:
Hi,
I wrote the 'autoimp' module , which allows you to import lazy modules:
from autoimp import * (Import lazy wrapper objects around all modules; "lazy
modules" will turn into normal modules when an attribute
is first accessed with getattr()).
from autoimp import A, B (Import specific lazy module wrapper objects).
The main point of autoimp is to make usage of the interactive Python prompt
|
by: kwatch |
last post by:
What is the condition of module name which is available in
'from .. import ..' statement ?
----------------------------------------
import os
print os.path # <module 'posixpath' from '/usr/local/
lib/python2.5/posixpath.pyc'>
from posixpath import sep # (no errors)
from os.path import sep # (no errors, wow!)
path = os.path
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
| |
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |