473,480 Members | 3,098 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Module imports during object instantiation

Hi,

I've been very confused about why this doesn't work. I mean I don't see any
reason why this has been made not to work.

class Log:

def __init__(self, verbose, lock = None):

if verbose is True:
self.VERBOSE = True
else: self.VERBOSE = False
if lock is None or lock != 1:
self.DispLock = False
else:
self.DispLock = threading.Lock()
self.lock = True

if os.name == 'posix':
self.platform = 'posix'
self.color = get_colors()

elif os.name in ['nt', 'dos']:
self.platform = 'microsoft'

try:
import SomeModule
except ImportError:
self.Set_Flag = None

if self.Set_Flag is not None:
self.color = SomeModule.get_colors_windows()

else:
self.platform = None
self.color = None

When I create an object the "import" part never gets executed. Is there a
reason behind it ?
I mean I'd like to keep my class as independent as I want. So that when
later I need to use it somewhere else, I don't need to know if it depends
on any modules.

Currently, the way I'm left is to globally go and import the module and set
a flag there.
Ritesh
--
If possible, Please CC me when replying. I'm not subscribed to the list.

Aug 10 '07 #1
6 1300
On Aug 11, 3:17 am, James Stroud <jstr...@mbi.ucla.eduwrote:
You do realize your import statement will only be called for nt and dos
systems don't you?
Yes. I would like to load a Windows Python Module (which is, say a
specific implementation for Windows only) in such a condition where I
find that the platform is Dos/NT.

Loading it globally doesn't make sense because when from the same
class an object is created on a non-windows platfom, it would be
waste. It would either ImportError or else just load the module and
never use it.

As per my understanding __init__ is executed only once during object
creation. For such situations (that I've explained above), I think
__init__() is the correct place to put imports.

Ritesh

Aug 12 '07 #2
Ritesh Raj Sarraf a écrit :
On Aug 11, 3:17 am, James Stroud <jstr...@mbi.ucla.eduwrote:
>You do realize your import statement will only be called for nt and dos
systems don't you?

Yes. I would like to load a Windows Python Module (which is, say a
specific implementation for Windows only) in such a condition where I
find that the platform is Dos/NT.

Loading it globally doesn't make sense because when from the same
class an object is created on a non-windows platfom, it would be
waste. It would either ImportError or else just load the module and
never use it.

As per my understanding __init__ is executed only once during object
creation. For such situations (that I've explained above), I think
__init__() is the correct place to put imports.

Nope.

The initializer will be called *each time* you instanciate the class.
And nothing prevents client code from calling it explicitelly as many
times as it wants - ok, this would be rather strange, but this is still
technically possible. What I mean that you have no assurance about the
number of times an initializer will be called.
wrt/ your problem, remember that top-level code is executed when the
module is loaded (either as a main program or as an imported module).
The canonical solution to os-specific imports is to handle them at the
top-level:

if os.name == 'posix:
from some_posix_module import get_colors
elif os.name in ['nt', 'dos']:
from some_nt_module import get_windows_color as get_colors
else:
get_colors = lambda: None # or any other sensible default value...

class SomeClass(object):
def __init__(self, *args, **kw):
self.colors = get_colors()
Aug 13 '07 #3
Bruno Desthuilliers wrote:
Ritesh Raj Sarraf a écrit :
>>
if lock is None or lock != 1:
self.DispLock = False
else:
self.DispLock = threading.Lock()
self.lock = True

if os.name == 'posix':
self.platform = 'posix'
self.color = get_colors()

elif os.name in ['nt', 'dos']:
self.platform = 'microsoft'

try:
import SomeModule
except ImportError:
self.Set_Flag = None

if self.Set_Flag is not None:
self.color = SomeModule.get_colors_windows()

else:
self.platform = None
self.color = None

When I create an object the "import" part never gets executed. Is there a
reason behind it ?

what does "print os.name" yields ?
On Windows: nt
On Linux: posix
>
>I mean I'd like to keep my class as independent as I want. So that when
later I need to use it somewhere else, I don't need to know if it depends
on any modules.
>

Then pass the module to the initializer. Python's modules are objects...
Yes, that's an option. But is that the only one?
To me it looks like an ugly way of doing.

Ritesh
--
If possible, Please CC me when replying. I'm not subscribed to the list.

Aug 13 '07 #4
Bruno Desthuilliers wrote:
Ritesh Raj Sarraf a écrit :

The initializer will be called *each time* you instanciate the class.
And nothing prevents client code from calling it explicitelly as many
times as it wants - ok, this would be rather strange, but this is still
technically possible. What I mean that you have no assurance about the
number of times an initializer will be called.
Yes, it should be called _each time_ I do an instantiation. But the point
is, I'm doing it only once. And I don't see people instantiating multiple
times. And even if you do, it should do separate imports.

log1 = Log()
log2 = Log()

Both the objects are separate from each other in every manner and they share
nothing.
>
wrt/ your problem, remember that top-level code is executed when the
module is loaded (either as a main program or as an imported module).
The canonical solution to os-specific imports is to handle them at the
top-level:

if os.name == 'posix:
from some_posix_module import get_colors
elif os.name in ['nt', 'dos']:
from some_nt_module import get_windows_color as get_colors
else:
get_colors = lambda: None # or any other sensible default value...

class SomeClass(object):
def __init__(self, *args, **kw):
self.colors = get_colors()
This is what I'm left with to do currently. But I doubt if that makes by
classes independent and to "Just Work". If someone was to cut/paste just
the class, it won't work. He'll have to go through the imports and figure
out which one relates to the class he want's to import and add similar code
to his.

Ritesh
--
If possible, Please CC me when replying. I'm not subscribed to the list.

Aug 13 '07 #5
Ritesh Raj Sarraf a écrit :
Bruno Desthuilliers wrote:
>Ritesh Raj Sarraf a écrit :

The initializer will be called *each time* you instanciate the class.
And nothing prevents client code from calling it explicitelly as many
times as it wants - ok, this would be rather strange, but this is still
technically possible. What I mean that you have no assurance about the
number of times an initializer will be called.

Yes, it should be called _each time_ I do an instantiation. But the point
is, I'm doing it only once. And I don't see people instantiating multiple
times.
You of course don't instanciate the same object more than once !-) What
I meant is that, while you can be reasonably confident that the
initializer will be call at least once (on instanciation), nothing
prevents user code to directly call it as many times he wants.
And even if you do, it should do separate imports.
Why so ? Using the import statement, modules are only imported once for
a given process, you know ? And FWIW, what are the chances your running
process will move from one platform to another ?-)
log1 = Log()
log2 = Log()

Both the objects are separate from each other in every manner and they share
nothing.
How can you tell ? In the common case, they at least share a pointer to
the Log class object, and depending on the implementation they can share
other things too.
>wrt/ your problem, remember that top-level code is executed when the
module is loaded (either as a main program or as an imported module).
The canonical solution to os-specific imports is to handle them at the
top-level:

if os.name == 'posix:
from some_posix_module import get_colors
elif os.name in ['nt', 'dos']:
from some_nt_module import get_windows_color as get_colors
else:
get_colors = lambda: None # or any other sensible default value...

class SomeClass(object):
def __init__(self, *args, **kw):
self.colors = get_colors()

This is what I'm left with to do currently. But I doubt if that makes by
classes independent and to "Just Work". If someone was to cut/paste just
the class, it won't work.
Obviously not. But the module is the basic unit of code in Python.
He'll have to go through the imports and figure
out which one relates to the class he want's to import and add similar code
to his.
I'm afraid you're confusing import, include and cut'n'paste (which is
probably the worst possible code-reuse technic)... If someone wants to
reuse your code, the normal way is to import your module (and eventually
subclass yourmodule.SomeClass to extend/customize it).

Aug 14 '07 #6
Ritesh Raj Sarraf a écrit :
Bruno Desthuilliers wrote:
>Ritesh Raj Sarraf a écrit :
>> if lock is None or lock != 1:
self.DispLock = False
else:
self.DispLock = threading.Lock()
self.lock = True

if os.name == 'posix':
self.platform = 'posix'
self.color = get_colors()

elif os.name in ['nt', 'dos']:
self.platform = 'microsoft'

try:
import SomeModule
except ImportError:
self.Set_Flag = None

if self.Set_Flag is not None:
self.color = SomeModule.get_colors_windows()

else:
self.platform = None
self.color = None

When I create an object the "import" part never gets executed. Is there a
reason behind it ?
what does "print os.name" yields ?

On Windows: nt
On Linux: posix
Mmm... I guess you didn't understood my question. I do know the os
module. You assert the "import" is never executed. Since it's only
executed on a non-posix platform, I asked on what platform you where
testing.

>
>>I mean I'd like to keep my class as independent as I want. So that when
later I need to use it somewhere else, I don't need to know if it depends
on any modules.

Then pass the module to the initializer. Python's modules are objects...

Yes, that's an option. But is that the only one?
No.
To me it looks like an ugly way of doing.
Really ? Why so ? You say you want to keep your class "as independant"
(you don't say from what, but...). Can you imagine a way to get less
coupling than passing appropriate parameters to the initializer ?
Aug 14 '07 #7

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

Similar topics

8
3831
by: Bo Peng | last post by:
Dear list, I am writing a Python extension module that needs a way to expose pieces of a big C array to python. Currently, I am using NumPy like the following: PyObject* res =...
3
1651
by: | last post by:
I'm picking up an 'IMPORTS' error for a simple database insert based on two input entry boxes in my form? It says an 'Imports' statement must preceede any declarations....... is this perahps the...
10
1878
by: Ron | last post by:
Hello, The following code works in a Form class module but not a standard module: Dim d1 As DateTime Format(d1, "MMMM") In a standard module I get a squigly line saying that an argument has...
2
1401
by: NH | last post by:
I have a module that handles creating a sql connection object as per below code. What do you think, is there a better way to do this? Imports System.Data Imports System.Data.SqlClient Imports...
2
1715
by: tobiah | last post by:
I am making a web app, made up of many modules that all need access to some important data, like the current session data, cookies, navigation history, post/get variables, etc. I decided to go...
9
1215
by: noamsml | last post by:
Hi, I am new to python and am currently writing my first application. One of the problems I quickly ran into, however, is that python's imports are very different from php/C++ includes in the...
32
5759
by: Matias Jansson | last post by:
I come from a background of Java and C# where it is common practise to have one class per file in the file/project structure. As I have understood it, it is more common practice to have many...
3
1444
by: Jugdish | last post by:
Why doesn't the following work? $HOME/pkg/__init__.py $HOME/pkg/subpkg/__init__.py $HOME/pkg/subpkg/a.py $HOME/pkg/subpkg/b.py # empty import a
0
182
by: norseman | last post by:
mercado mercado wrote: =================================== I started to import a module using its path and now see what you mean. Python is missing the concept: Programmer dictates what machine...
0
7061
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,...
0
7110
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...
0
7030
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...
0
5367
agi2029
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,...
1
4799
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...
0
4503
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...
0
1313
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 ...
1
574
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
210
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...

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.