473,659 Members | 2,680 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Parametrized module import

I have a module whose behaviour needs to be configurable. The module
needs to decide, the first time it is imported, beteween alternative
interfaces it presents.

Currently, I set some environment variables which select the desired
behaviour, and the module inspects those variables to determine the
mode in which it should set itself up. I would prefer a pure Python
solution, rather than one which depends on external state.

Can you recommend any approaches, or warn against the pitfalls of some
approaches?

Jul 18 '05 #1
17 1874
Jacek Generowicz <ja************ **@cern.ch> wrote:
I have a module whose behaviour needs to be configurable. The module
needs to decide, the first time it is imported, beteween alternative
interfaces it presents.

Currently, I set some environment variables which select the desired
behaviour, and the module inspects those variables to determine the
mode in which it should set itself up. I would prefer a pure Python
solution, rather than one which depends on external state.

Can you recommend any approaches, or warn against the pitfalls of some
approaches?


You could create another module called "config" or "cfg"
which contains some global variables. You import it into
your configurable module as well as into your main program.
Then you can configure the module's behaviour via those
global variables before importing the module.

Something like this:

#--- File config.py: ---
foo_interface_m ode = 0 # default

#--- File your_module.py: ---
import config
if config.foo_inte rface_mode == 0:
... this interface
else:
... that interface

#--- File main_program.py : ---
import config
config.foo_inte rface_mode = 1
import your_module

Best regards
Oliver

--
Oliver Fromme, Konrad-Celtis-Str. 72, 81369 Munich, Germany

``All that we see or seem is just a dream within a dream.''
(E. A. Poe)
Jul 18 '05 #2
Oliver Fromme <ol**@haluter.f romme.com> writes:
You could create another module called "config" or "cfg"
which contains some global variables. You import it into
your configurable module as well as into your main program.
Then you can configure the module's behaviour via those
global variables before importing the module.


Yes, my initial crappy prototype idea was to add configuration
information to the sys module, but this variation is much neater
.... in fact, after the first 2 minutes of thinking about it, it looks
perfect :-)

However, one thing which keeps bothering me about the whole business,
is the possibilty of importing the module (with your chosen
configuration) after it has already been imported, without you knowing
it, with a different configuration. Ideally there should be some
warning about the fact that the configuration you specified is being
ignored as a result of the module already being imported ... and I
don't see how to achieve this.

Jul 18 '05 #3
Heather Coppersmith <me@privacy.net > wrote:
Jacek Generowicz <ja************ **@cern.ch> wrote:
Oliver Fromme <ol**@haluter.f romme.com> writes:
You could create another module called "config" or "cfg" which
contains some global variables. You import it into your
configurable module as well as into your main program. Then
you can configure the module's behaviour via those global
variables before importing the module.


Yes, my initial crappy prototype idea was to add configuration
information to the sys module, but this variation is much neater
... in fact, after the first 2 minutes of thinking about it, it
looks perfect :-)

However, one thing which keeps bothering me about the whole
business, is the possibilty of importing the module (with your
chosen configuration) after it has already been imported,
without you knowing it, with a different configuration. Ideally
there should be some warning about the fact that the
configuration you specified is being ignored as a result of the
module already being imported ... and I don't see how to achieve
this.


Upon import, a module's "top level" code is executed, so try a
variation on this theme at the top level of your module:


It's only executed when the module is imported for the
_first_ time, so that wouldn't work.

However, the problem can be solved by not modifying a
global variable in the "config" module directly, but by
using a function which allows only one call.

#--- File config.py: ---
foo_interface_m ode = None
def set_foo_interfa ce_mode (mode):
if foo_interface_m ode is None:
foo_interface_m ode = mode
else:
raise "foo_interface_ mode may only be set once"

#--- File your_module.py: ---
import config
if config.foo_inte rface_mode is None:
raise "foo_interface_ mode has not been set"
elif config.foo_inte rface_mode == 0:
... this interface
else:
... that interface

#--- File main_program.py : ---
import config
config.set_foo_ interface_mode (1)
import your_module

Of course, you could use assert instead of raise, or just
print a warning and go on. Whatever you prefer.

Best regards
Oliver

--
Oliver Fromme, Konrad-Celtis-Str. 72, 81369 Munich, Germany

``All that we see or seem is just a dream within a dream.''
(E. A. Poe)
Jul 18 '05 #4
Heather Coppersmith <me@privacy.net > writes:
Upon import, a module's "top level" code is executed,
Yes, but only on the _first_ import. On subsequent imports the system
notices that the module has already imported, and doesn't execute
anything in the module, it just binds a name to the already imported
module ...
so try a variation on this theme at the top level of your module:

i_am_configured = False

if i_am_configured :
print 'i am already configured'
else:
import my_configuratio n_module
configure_mysel f( )
i_am_configured = True


.... so the first branch will _never_ get executed.

My question is exactly about this problem: nothing gets executed on
the second import, so there's nowhere for me to put the "already
configured" message.

Jul 18 '05 #5
Oliver Fromme <ol**@haluter.f romme.com> writes:
However, the problem can be solved by not modifying a
global variable in the "config" module directly, but by
using a function which allows only one call.

#--- File config.py: ---
foo_interface_m ode = None
def set_foo_interfa ce_mode (mode):
if foo_interface_m ode is None:
foo_interface_m ode = mode
else:
raise "foo_interface_ mode may only be set once"


But there must be a default configuration, so you can't check for
None. I typically deal with these situations by using functions which
replace themselves when called:

def configure():
print "Configurin g ..."
global configure
def configure():
print "Sorry, already configured."

But this doesn't quite solve the problem I'm trying to solve, which is
to warn, at the time the import statement is executed, that the
configuration which is in place is not being respected.

There's nothing wrong with the user changing the mode twenty times
before the first import. I guess the imported module could block
further configuration changes, and the warning can come when you try
to change the configuration _after_ the first import.

Jul 18 '05 #6
On 08 Jul 2004 09:43:31 +0200
Jacek Generowicz <ja************ **@cern.ch> threw this fish to the penguins:
I have a module whose behaviour needs to be configurable. The module
needs to decide, the first time it is imported, beteween alternative
interfaces it presents.

Currently, I set some environment variables which select the desired
behaviour, and the module inspects those variables to determine the
mode in which it should set itself up. I would prefer a pure Python
solution, rather than one which depends on external state.

Can you recommend any approaches, or warn against the pitfalls of some
approaches?


You might look at the way pygtk does it. I haven't peeked inside, but the
api is:

import pygtk
pygtk.require(' 2.0') # or '1.2' or some other version
import gtk # uses state set by require() to load the appropriate version

The pygtk.py file looks quite reusable with hardly any change...

See: http://www.pygtk.org
-- George
--
"Are the gods not just?" "Oh no, child.
What would become of us if they were?" (CSL)
Jul 18 '05 #7
george young <gr*@ll.mit.edu > writes:
You might look at the way pygtk does it. I haven't peeked inside,
Here is the relevant part ...

def require(version ):
global _pygtk_required _version

if _pygtk_required _version != None:
assert _pygtk_required _version == version, \
"a different version of gtk was already required"
return

assert not sys.modules.has _key('gtk'), \
"pygtk.require( ) must be called before importing gtk"

...
but the api is:

import pygtk
pygtk.require(' 2.0') # or '1.2' or some other version
import gtk # uses state set by require() to load the appropriate version


Yup ... but now I'm being put under pressure to make the API thus:

import foo
foo.config....

which doesn't thrill me at all, for a plethora of implementation
detail related reasons which are not interesting here.

Thanks for the poniter, anyway.
Jul 18 '05 #8
Jacek Generowicz wrote:
I have a module whose behaviour needs to be configurable. The module
needs to decide, the first time it is imported, beteween alternative
interfaces it presents.

Currently, I set some environment variables which select the desired
behaviour, and the module inspects those variables to determine the
mode in which it should set itself up. I would prefer a pure Python
solution, rather than one which depends on external state.

Can you recommend any approaches, or warn against the pitfalls of some
approaches?


Following `explicit is better than implicit` I'd prefer to have a huge
interface class or object that would be instantiated with parameters.
Something like this:

from myModule import myModule

myModule.tweak( <blah>)

....

myModule.doSome thing()

Of course, this solution might not fit your needs.

regards,
anton.
Jul 18 '05 #9
anton muhin <an********@ram bler.ru> writes:
Of course, this solution might not fit your needs.


In this case, I am afraid that it does not.
Jul 18 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
2932
by: Paul Rubin | last post by:
That's what the Python style guides advise. They don't seem to like def frob(x): import re if re.search('sdfxyz', x): ... instead preferring that you pollute your module's global namespace with the names of all your imports. What's the point of that? It gets worse when you want to do something like
5
2013
by: dody suria wijaya | last post by:
I found this problem when trying to split a module into two. Here's an example: ============== #Module a (a.py): from b import * class Main: pass ============== ==============
4
8754
by: Bo Peng | last post by:
Dear list, What I would like to do is something like: In myModule.py ( a wrapper module for different versions of the module), if lib == 'standard': from myModule_std import * elsif lib == 'optimized' from myModule_op import *
6
1837
by: kimes | last post by:
I've just started digging into how python works.. I found that other mudules are clearly declared like one file per a module.. But the only os.path doesn't have their own file.. ye I know is has actually depending on os like in my case posixpath.. What I'd love to know is.. when I call import os.path.. how happened under the hood?
2
2147
by: Matthias Kramm | last post by:
Hi All, I'm having a little bit of trouble using the "imp" module to dynamically import modules. It seems that somehow cyclic references of modules don't work. I'm unable to get the following to work: I've got the following files: web/__init__.py
3
5417
by: Mudcat | last post by:
I have a directory structure that contains different modules that run depending on what the user selects. They are identical in name and structure, but what varies is the content of the functions. They will only need to be run once per execution. Example (directory level): Sys1: A B C
3
2003
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
6
1715
by: ai | last post by:
It assumes that there is a module A which have two global variables X and Y. If I run "import A" in the IDLE shell, then I can use A.X and A.Y correctly. But if I want to change the module A and then delete the variable Y, I find I can use A.Y just the same as before! In fact, I have tried all the following methods but can't remove the A.Y: execute "import A" again "reload(A)" "del A; import A" Yes, if you use "del A.Y", it works. But...
0
2153
by: Fredrik Lundh | last post by:
Jeff Dyke wrote: so how did that processing use the "mymodulename" name? the calling method has nothing to do with what's considered to be a local variable in the method being called, so that only means that the name is indeed available in the global scope.
0
8330
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,...
0
8850
Oralloy
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...
0
8746
jinu1996
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...
1
8523
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8626
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6178
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5649
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();...
2
1975
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1737
bsmnconsultancy
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...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.