473,387 Members | 1,942 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

This coding style bad practise?

Hi all,

I created a class which creates a relative unique id string, now my
program just works fine and as expected but somehow I get the feeling
that I misused the __repr__ since I guess people expect to 'execute' a
function in an instance instead of using it's representation string of
the instance itself, could you elaborate whether you find this bad
practice and if yes what would have been a better way to do it?

TIA

----- script -----
import string
import time

class IDGenerator(object):
"""(serverID,subversion_length)
Create an ID from the server name, datetimestamp and version number.
Calling the instance returns the ID using the __repr__ class function

Example usage:
>>> id = idgen('01',4)
>>> id 01_20060424_151903_1 >>> id 01_20060424_151905_2 >>> id 01_20060424_151905_3 >>> id 01_20060424_151906_4 >>> id 01_20060424_151907_1 >>>
>>> id = idgen(04,100)
>>> id

4_20060424_152043_001

"""

def __init__(self,serverID,subversion_length):
self.ID = str(serverID)
self.length = int(subversion_length)
fill_length = len(str(self.length))

def fill(number):
return(string.zfill(number,fill_length))
self.fill = fill
def __repr__(self):
# If the subversion length has been reached or the generator has not
# been defined, (re)define it, otherwise return the next value of the
# subversion.
try:
return_value = self.range_gen.next()

except:
self.range_gen = ( number for number in range(1,self.length+1) )
return_value = self.range_gen.next()

# Create the version stamp.
return_value = self.ID +\
time.strftime("_%Y%m%d_%H%M%S_",time.gmtime())+\
self.fill(return_value)

# And return it.
return(return_value)

----- script -----

--
mph
May 3 '06 #1
11 1162
Martin P. Hellwig a écrit :
Hi all,

I created a class which creates a relative unique id string, now my
program just works fine and as expected but somehow I get the feeling
that I misused the __repr__ since I guess people expect to 'execute' a
function in an instance instead of using it's representation string of
the instance itself, could you elaborate whether you find this bad
practice and if yes what would have been a better way to do it?


Why not just use the call operator instead ? ie:
id = IDGenerator(...)
id() 01_20060424_151903_1 id()

01_20060424_151905_2

May 3 '06 #2

Martin P. Hellwig wrote:
Hi all,

I created a class which creates a relative unique id string, now my
program just works fine and as expected but somehow I get the feeling
that I misused the __repr__ since I guess people expect to 'execute' a
function in an instance instead of using it's representation string of
the instance itself, could you elaborate whether you find this bad
practice and if yes what would have been a better way to do it?

TIA


Rather than comment on the style of using a class, I'll just suggest an
alternative.
You can use a generator function, which yields the next id when called;
at least that's
how I'd implement an IDgenerator.

Cheers,

Keir.

May 3 '06 #3
Bruno Desthuilliers wrote:
Martin P. Hellwig a écrit :
I created a class which creates a relative unique id string, now my
program just works fine and as expected but somehow I get the feeling
that I misused the __repr__ since I guess people expect to 'execute' a
function in an instance instead of using it's representation string of
the instance itself, could you elaborate whether you find this bad
practice and if yes what would have been a better way to do it?


Why not just use the call operator instead ? ie:
>>> id = IDGenerator(...)
>>> id() 01_20060424_151903_1 >>> id()

01_20060424_151905_2


because that shadows a builtin?

sorry, could not resist :-)

Cheers,

Carl Friedrch Bolz

May 3 '06 #4
Bruno Desthuilliers wrote:
Martin P. Hellwig a écrit :
I created a class which creates a relative unique id string, now my
program just works fine and as expected but somehow I get the feeling
that I misused the __repr__ since I guess people expect to 'execute' a
function in an instance instead of using it's representation string of
the instance itself, could you elaborate whether you find this bad
practice and if yes what would have been a better way to do it?


Why not just use the call operator instead ? ie:
>>> id = IDGenerator(...)
>>> id() 01_20060424_151903_1 >>> id()

01_20060424_151905_2


because that shadows a builtin?

sorry, could not resist :-)

Cheers,

Carl Friedrch Bolz

May 3 '06 #5
Bruno Desthuilliers wrote:
<cut>

Why not just use the call operator instead ? ie:
>>> id = IDGenerator(...)
>>> id() 01_20060424_151903_1 >>> id() 01_20060424_151905_2


Because of:
id = IDGenerator("01",99)
id() Traceback (most recent call last):
File "<pyshell#1>", line 1, in ?
id()
TypeError: 'IDGenerator' object is not callable


But i do appreciate your comment, thanks!

--
mph
May 3 '06 #6
keirr wrote:
Martin P. Hellwig wrote:
Hi all,

I created a class which creates a relative unique id string, now my
program just works fine and as expected but somehow I get the feeling
that I misused the __repr__ since I guess people expect to 'execute' a
function in an instance instead of using it's representation string of
the instance itself, could you elaborate whether you find this bad
practice and if yes what would have been a better way to do it?

TIA


Rather than comment on the style of using a class, I'll just suggest an
alternative.
You can use a generator function, which yields the next id when called;
at least that's
how I'd implement an IDgenerator.

Cheers,

Keir.


Thanks for your comment, I do use a generator in my class because I
wanted to wrap my subversion when its on its end I had a choice of
looping in with an if check or using a generator with try except, this
time I choose a generator, though mostly I directly use a generator for
these type of functions.

--
mph
May 3 '06 #7
Am Donnerstag 04 Mai 2006 01:04 schrieb Martin P. Hellwig:
Because of:
> id = IDGenerator("01",99)
> id()


Traceback (most recent call last):
File "<pyshell#1>", line 1, in ?
id()
TypeError: 'IDGenerator' object is not callable


But i do appreciate your comment, thanks!


You need to define a __call__(self)-method on your class so that instances are
callable... Basically, what Bruno was saying, is that you rename your
__repr__(self) to __call__(self), and see what happens.

--- Heiko.
May 4 '06 #8
Carl Friedrich Bolz wrote:
Bruno Desthuilliers wrote:
Martin P. Hellwig a écrit :
I created a class which creates a relative unique id string, now my
program just works fine and as expected but somehow I get the feeling
that I misused the __repr__ since I guess people expect to 'execute'
a function in an instance instead of using it's representation string
of the instance itself, could you elaborate whether you find this bad
practice and if yes what would have been a better way to do it?

Why not just use the call operator instead ? ie:
>>> id = IDGenerator(...)
>>> id()

01_20060424_151903_1
>>> id()

01_20060424_151905_2

because that shadows a builtin?


oops :(
sorry, could not resist :-)


<op>
idgen = IDGenerator(...)
idgen()

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
May 4 '06 #9
Martin P. Hellwig wrote:
Bruno Desthuilliers wrote:
<cut>

Why not just use the call operator instead ? ie:
>>> id = IDGenerator(...)
>>> id()

01_20060424_151903_1
>>> id()

01_20060424_151905_2


Because of:
> id = IDGenerator("01",99)
> id()


Traceback (most recent call last):
File "<pyshell#1>", line 1, in ?
id()
TypeError: 'IDGenerator' object is not callable
>


Of course - you have to overload the call operator for this to work.
Just rename IDGenerator.__repr__ to IDGenerator.__call__, and I garantee
this will work - and will be *much* more cleaner than abusing __repr__.

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
May 4 '06 #10
bruno at modulix wrote:
Martin P. Hellwig wrote:
Bruno Desthuilliers wrote:
<cut>
Why not just use the call operator instead ? ie:

>>> id = IDGenerator(...)
>>> id()
01_20060424_151903_1
>>> id()
01_20060424_151905_2

Because of:
>> id = IDGenerator("01",99)
>> id()
Traceback (most recent call last):
File "<pyshell#1>", line 1, in ?
id()
TypeError: 'IDGenerator' object is not callable


Of course - you have to overload the call operator for this to work.
Just rename IDGenerator.__repr__ to IDGenerator.__call__, and I garantee
this will work - and will be *much* more cleaner than abusing __repr__.

Thanks! That was the thing I was looking for!

--
mph
May 4 '06 #11
<cut>

Thanks for the input folks!
I adapted my script to the given suggestions and it's now far more
'logical', for reference I added it below.

--
mph

----- script -----
import string
import time

class IDGenerator(object):
"""(leading_id, subversion_length, tz) # tz = 'local' or 'gm' (default)
Create an ID from a given string, a current datetimestamp and version
number which wraps around at given subversion_length.

Example usage:
>>> id = IDGenerator('01',2)
>>> id() '01_20060504_112304_1' >>> id() '01_20060504_112306_2' >>> id() '01_20060504_112307_1' >>>
>>> id = IDGenerator(0005,99) # Note that an int will be cast to a string!
>>> id() '5_20060504_112324_01' >>> id() '5_20060504_112327_02' >>> id <class '__main__.IDGenerator'> previous ID is 5_20060504_112324_01 and
current ID is 5_20060504_112327_02 >>>


"""

def __init__(self,leading_id, subversion_length, timezone='gm'):
self.id = str(leading_id)
self.length = int(subversion_length)
fill_length = len(str(self.length))
self.current = None
self.previous = None

def fill(number):
return(string.zfill(number,fill_length))
self.fill = fill

if timezone == 'local':
self.timeset = time.localtime
else:
self.timeset = time.gmtime
def __call__(self):
# If the subversion length has been reached or the generator has not
# been defined, (re)define it, otherwise return the next value of the
# subversion.
try:
return_value = self.range_gen.next()

except:
self.range_gen = ( number for number in range(1,self.length+1) )
return_value = self.range_gen.next()

# Create the version stamp.
return_value = self.id +\
time.strftime("_%Y%m%d_%H%M%S_",self.timeset())+\
self.fill(return_value)

# Copy the current ID to the previous and assign a new one to current.
self.previous = self.current
self.current = return_value

# And return it.
return(self.current)

def __repr__(self):
return(str(self.__class__) +
' previous ID is ' +
str(self.previous) +
' and current ID is ' +
str(self.current))

----- script -----
May 4 '06 #12

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

Similar topics

1
by: Kruse | last post by:
Hi, Is Possible to alter the "disabled" style? I have got <input name="test" value="1" disabled> This makes the input field gray and shadow.
13
by: TheKeith | last post by:
Is it just me or does opera and ie not render the float style properly? IE does a sucky job at it, but opera makes a total mess; Mozilla/Firefox renders it correctly however. I'm just trying to be...
144
by: Natt Serrasalmus | last post by:
After years of operating without any coding standards whatsoever, the company that I recently started working for has decided that it might be a good idea to have some. I'm involved in this...
8
by: s.subbarayan | last post by:
Dear all, In one of our projects in a document about C coding standard it is stated as "Always check a pointer is NULL before calling free. Always set a free'd pointer to NULL to try to protect...
30
by: Felix Kater | last post by:
Hi, in some cases like dynamic memory allocation I find it convenient to (ab-)use for() or while() like this: /* (allocate memory) */ for(;;){ /* alternatively: while(TRUE){ */
4
by: Dotnetjunky | last post by:
Hi, So far, I've found tons of documents describing recommended coding standards for C#, but not a single piece on VB.NET yet. Anybody here knows such a coding standards guideline on VB.NET...
13
by: benben | last post by:
Is there an effort to unify the c++ coding standard? Especially identifier naming. Not a big issue but it would be annoying to have to incorporate different coding styles simultaneously when...
3
by: Peter D. | last post by:
I have been programming PHP for a while now and always seem to run into the same problem when working on more than trivial apps. Most of my coding is for personal projects anyway so it really isn't...
7
by: MJ_India | last post by:
Style 1: struct my_struct { ... }; typedef my_struct my_struct_t; Style 2: typedef struct my_struct {
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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
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...

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.