473,795 Members | 2,391 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Class optimization at runtime

I would like to optimize my classes at run time. The question
is where to put my "if" statement.
-Inside __main__?
if option:
class Foo:
def __init__:
#do stuff
else:
class Foo:
def __init__:
#do other stuff
-Inside class definition?
class Foo:
if option:
def __init__:
#do stuff
else:
def __init__:
#do other stuff
-Inside each method definition?
class Foo:
def __init__:
if option:
#do stuff
else:
#do other stuff

Class instances will be created millions of times and the
method's on them called even more so whatever brings the most
speed will be used. I fear that the more readable way to do it
is also the slowest.

Thanks in advance,
-Brian
Jul 18 '05 #1
8 1437
Kind of hard to tell what you are trying to accomplish
but I'll try. Define the class with no if/else statements.
They only get parsed once. It is the "class instance"
creations that may get created millions of times. They
will be inside your logical structure.

class Foo:
def __init__(self):
# do stuff

class Bar:
def __init__(self):
# do stuff

if option: x=Foo()
else: x=Bar()

HTH,
Larry Bates
<br****@temple. edu> wrote in message
news:ma******** *************** *************** @python.org...
I would like to optimize my classes at run time. The question
is where to put my "if" statement.
-Inside __main__?
if option:
class Foo:
def __init__:
#do stuff
else:
class Foo:
def __init__:
#do other stuff
-Inside class definition?
class Foo:
if option:
def __init__:
#do stuff
else:
def __init__:
#do other stuff
-Inside each method definition?
class Foo:
def __init__:
if option:
#do stuff
else:
#do other stuff

Class instances will be created millions of times and the
method's on them called even more so whatever brings the most
speed will be used. I fear that the more readable way to do it
is also the slowest.

Thanks in advance,
-Brian

Jul 18 '05 #2
Larry Bates wrote:
Kind of hard to tell what you are trying to accomplish
but I'll try. Define the class with no if/else statements.
They only get parsed once. It is the "class instance"
creations that may get created millions of times. They
will be inside your logical structure.
Yup.
class Foo:
def __init__(self):
# do stuff

class Bar:
def __init__(self):
# do stuff

if option: x=Foo()
else: x=Bar()


I don't see anything wrong with his original suggestion, provided that
makes the rest of the code simpler:
class Foo:
if option:
def __init__:
#do stuff
else:
def __init__:
#do other stuff


That 'if' also gets run only once - when the class is created.

Note that if your class instances only have a few instance variables,
the most effective optimization may be something quite else: To make
them subclasses of 'object', and define __slots__. A program of mine
ran in about half the time after doing so. There are a number of
dangers involved with __slots__, though. Check the reference manual.

For other optimization hints, see section 1.5 of the Python Programming
FAQ at <http://www.python.org/doc/faq/programming.htm l>.

--
Hallvard
Jul 18 '05 #3
On Mon, 2 Aug 2004 16:06:03 -0500,
"Larry Bates" <lb****@swamiso ft.com> wrote:
Kind of hard to tell what you are trying to accomplish
but I'll try. Define the class with no if/else statements.
They only get parsed once. It is the "class instance"
creations that may get created millions of times. They
will be inside your logical structure. class Foo:
def __init__(self):
# do stuff class Bar:
def __init__(self):
# do stuff if option: x=Foo()
else: x=Bar()
Similarly:

class FooWithOption:
def __init__( self ):
# whatever

class FooWithoutOptio n:
def __init__( self ):
# whatever

if option:
Foo = FooWithOption
else:
Foo = FooWithoutOptio n

x = Foo( )

Alternatively:

module WithOption:
class Foo:
# whatever
class Bar:
# whatever

module WithOutOption:
class Foo:
# whatever
class Bar:
# whatever

if option:
from WithOption import *
else:
from WithoutOption import *

x = Foo( )

I guess it depends on how similar the with and without classes are as to
which one will be easier to maintain.

In either case, there's only one test and no additional overhead at
class instantiation time.
HTH,
Larry Bates


Regards,
Dan

--
Dan Sommers
<http://www.tombstoneze ro.net/dan/>
Never play leapfrog with a unicorn.
Jul 18 '05 #4
Dan Sommers wrote:
Alternativel y:

module WithOption:
class Foo:
# whatever
class Bar:
# whatever

module WithOutOption:
class Foo:
# whatever
class Bar:
# whatever

if option:
from WithOption import *
else:
from WithoutOption import *

x = Foo( )


Or even better:

if option:
import WithOption as FooModule
else:
import WithoutOption as FooModule

x = FooModule.Foo( )

(I twitch every time I see 'from X import *' ...)

Jeff Shannon
Technician/Programmer
Credit International

Jul 18 '05 #5
Jeff Shannon wrote:
Or even better:

if option:
import WithOption as FooModule
else:
import WithoutOption as FooModule

x = FooModule.Foo( )

(I twitch every time I see 'from X import *' ...)


That, and mixed-case module names -- and no, I'm not advertising
all-uppercase here...

Peter
Jul 18 '05 #6
On Tue, 03 Aug 2004 23:46:32 +0200,
Peter Otten <__*******@web. de> wrote:
Jeff Shannon wrote:
Or even better:

if option:
import WithOption as FooModule
else:
import WithoutOption as FooModule

x = FooModule.Foo( )

(I twitch every time I see 'from X import *' ...)

Yep, you're right. I always forget about the "as" option.
That, and mixed-case module names -- and no, I'm not advertising
all-uppercase here...


My mistake again. The names I chose were for illustrative and
explicative purposes only; nothing else was (meant to be) implied.

For the record, then, it would look like this:

if option:
import optionon as optionmodule
else:
import optionoff as optionmodule

x = optionmodule.Fo o( )

(assuming we can live with an Initialcaps class name).

It also now strikes me that a package might be appropriate here: Let
__init__.py sort things out and set up the package's namespace
accordingly; then the rest of the program would just use the package
obliviously. But:

- __init__.py has to have access to the option variable (solutions
abound; good solutions are less plentiful and vary over time and
space);

- given (a) my recent track record for getting the details correct
and (b) my lack of experience with the package system, I humbly
leave the rest of such a solution to the interested reader.

Regards,
Dan

--
Dan Sommers
<http://www.tombstoneze ro.net/dan/>
Never play leapfrog with a unicorn.
Jul 18 '05 #7
Dan Sommers <me@privacy.net > wrote in message news:<m2******* *****@unique.fu lly.qualified.d omain.name.yeah .right>...
On Tue, 03 Aug 2004 23:46:32 +0200,
Peter Otten <__*******@web. de> wrote:
Jeff Shannon wrote:
Or even better:

if option:
import WithOption as FooModule
else:
import WithoutOption as FooModule

x = FooModule.Foo( )

(I twitch every time I see 'from X import *' ...)


Yep, you're right. I always forget about the "as" option.
That, and mixed-case module names -- and no, I'm not advertising
all-uppercase here...


My mistake again. The names I chose were for illustrative and
explicative purposes only; nothing else was (meant to be) implied.

For the record, then, it would look like this:

if option:
import optionon as optionmodule
else:
import optionoff as optionmodule

x = optionmodule.Fo o( )

(assuming we can live with an Initialcaps class name).

It also now strikes me that a package might be appropriate here: Let
__init__.py sort things out and set up the package's namespace
accordingly; then the rest of the program would just use the package
obliviously. But:

- __init__.py has to have access to the option variable (solutions
abound; good solutions are less plentiful and vary over time and
space);

- given (a) my recent track record for getting the details correct
and (b) my lack of experience with the package system, I humbly
leave the rest of such a solution to the interested reader.


How about the pygtk style "require":
import pygtk
pygtk.require(' 2.0')
import gtk # uses state set by the "require" call.

This always seems a clean interface to me. Much safer and cleaner than
something peeking at a global (or environment) variable.
Jul 18 '05 #8
On 9 Aug 2004 06:59:47 -0700,
gr*@ll.mit.edu (george young) wrote:
How about the pygtk style "require":
import pygtk
pygtk.require(' 2.0')
import gtk # uses state set by the "require" call. This always seems a clean interface to me. Much safer and cleaner
than something peeking at a global (or environment) variable.


Our mileage has varied. That one always seemed very unclean to me.

In my mind, pygtk sits on top of gtk, and that interface requires gtk to
look "up" to figure out what to do. Nothing inside gtk should depend on
(or even know about) anything inside pygtk.

Regards,
Dan

--
Dan Sommers
<http://www.tombstoneze ro.net/dan/>
Never play leapfrog with a unicorn.
Jul 18 '05 #9

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

Similar topics

1
2389
by: Andrew James | last post by:
All, I'm having some trouble with understanding python's importing behaviour in my application. I'm using psyco to optimise part of my code, but I'm not sure whether it inherits throughout the rest of my application (read this as for any imported module) if I import in in a 'higher-level' module. For example: A.py ====
10
2846
by: florian kno | last post by:
hello all! i'm using gcc 3.2 on linux. i have a (self developed) matrix class: class cMatrix { // unneccessary info stripped .... double *data; // matrix data is stored in a heap array cMatrix row(const int& r) const;
10
1500
by: Lord Labakudas | last post by:
Hi, I have a very simple question. Is int a predefined class in the standard C++ library. If yes, is it typedef'd as int somewhere ? I wish to know this because, I wish to create a class that has all the functionalities of int, but is also derived from another base class. For example, class Tuple: public Data, public int {
3
3282
by: John C | last post by:
Hi, I am a little uncertain about the concept of passing a reference to a class to another instance of a class. for instance I thought that the following was ok: Network network = Network(); Population pool = Population(& network); .... but this doesnt seem to work.. however the following works... Network * network = new Network();
9
2404
by: Rune | last post by:
Is it best to use double quotes and let PHP expand variables inside strings, or is it faster to do the string manipulation yourself manually? Which is quicker? 1) $insert = 'To Be'; $sentence = "$insert or not $insert. That is the question."; or
0
1312
by: Adam Sandler | last post by:
Hello, Using VWD 2005 here... I've noticed I've got .NET services on my system here: the .NET Runtime Optimization service and ASP.NET State service. I've noticed when the ASP.NET State service starts, it stops the .NET Runtime Optimization service. Does anyone know why this happens? Also, if the State service clobbers the Optimization service then why is the Optimization service there in the first place? Thanks!
15
3538
by: Juha Nieminen | last post by:
I'm sure this is not a new idea, but I have never heard about it before. I'm wondering if this could work: Assume that you have a common base class and a bunch of classes derived from it, and you want to make a deque which can contain any objects of any of those types. Normally what you would have to do is to make a deque or vector of pointers of the base class type and then allocate each object dynamically with 'new' and store the...
9
1347
by: =?ISO-8859-1?Q?Janne_H=E4rk=F6nen?= | last post by:
Hello, Is there a simple way to resolve declaring class of a method at runtime ? Consider this simple example: $ python Python 2.5.1 (r251:54863, May 18 2007, 16:56:43) on cygwin Type "help", "copyright", "credits" or "license" for more information.
32
2094
by: Immortal Nephi | last post by:
I want to know if the practice is the best. Do I need to place inline keyword inside class definition or outside member function definition. For example class A { public: A(); ~A();
0
10438
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
10214
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
10164
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
9042
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, 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...
1
7540
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
6780
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();...
0
5563
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4113
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
2
3727
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.