473,608 Members | 2,090 Online
Bytes | Software Development & Data Engineering Community
+ 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 1309
On Aug 11, 3:17 am, James Stroud <jstr...@mbi.uc la.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.uc la.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_modu le import get_colors
elif os.name in ['nt', 'dos']:
from some_nt_module import get_windows_col or as get_colors
else:
get_colors = lambda: None # or any other sensible default value...

class SomeClass(objec t):
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_modu le import get_colors
elif os.name in ['nt', 'dos']:
from some_nt_module import get_windows_col or as get_colors
else:
get_colors = lambda: None # or any other sensible default value...

class SomeClass(objec t):
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_modu le import get_colors
elif os.name in ['nt', 'dos']:
from some_nt_module import get_windows_col or as get_colors
else:
get_colors = lambda: None # or any other sensible default value...

class SomeClass(objec t):
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.Some Class 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
3851
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 = PyArray_FromDimsAndData(1, int*dim, PyArray_DOUBLE, char*buf); Users will get a Numeric Array object and can change its values (and actually change the underlying C array).
3
1661
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 '@' symbol?? Any help appreciated! Thanks Jason
10
1895
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 not been specified for parameter format... So I tried this:
2
1409
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 System.Configuration.ConfigurationManager Public Module DBConnections 'Handles Opening and Closing connections to the Database Public objConnection As SqlConnection
2
1724
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 with the 'Borg' idea, by assigning the __dict__ of an object to a class variable so that each instantiation of the Borg() would share the same data. That way I can either pass the Borg around, or just Borg() it if I need it in some obscure place.
9
1225
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 sense that they completely wrap the imported script in a module object. One of the problems with this was that a plugin system that I am making requires use of objects, classes and the such from the original script. Thus, on one hand, I am hesitant...
32
5800
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 classes in a Python module/file. What is the motivation behind it, would it be a bad idea to have a guideline in your project that promotes a one class per file structure (assuming most of the programmers a background similar to mine)?
3
1458
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 does. (I come from assembly. If the hardware can do it, so can I.) sys.path can be modified to switch between file sets (prod/test). if a global is set one way, use the normal paths,
0
8063
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8003
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
8498
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...
1
8152
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
8341
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...
0
3962
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...
1
2474
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
1
1598
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1331
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.