[python 2.3.3, x86 linux]
I recently found myself writing something like:
def get_connection( ):
if tcp_conn():
if server_allows_c onn():
return 'good_conn'
else:
return 'bad_auth'
else:
return 'no_server'
cn = get_connection( )
if cn == 'good_con': ...
This is obviously just evil, since a misspelling in the string
return is treacherous. I'm considering function attributes:
def get_connection( ):
if tcp_conn():
if server_allows_c onn():
return get_connection. GOOD
else:
return get_connection. BAD_AUTH
else:
return get_connection. NO_SERVER
get_connection. GOOD = 1
get_connection. BAD_AUTH = 2
get_connection. NO_SERVER = 3
If I put this function in it's own module, the solution is obvious:
GOOD_CONN = 1
def get_connection( ):
...
return GOOD_CONN
But if this is a small utility function that belongs inside a
larger module/class, I would like to have it's return values
closely associated with the function, not just another value in
the parent class.
Is anybody using function attributes like this?
Is this good python style?
-- George Young
--
"Are the gods not just?" "Oh no, child.
What would become of us if they were?" (CSL) 8 1413
george young wrote: This is obviously just evil, since a misspelling in the string return is treacherous. I'm considering function attributes:
def get_connection( ): if tcp_conn(): if server_allows_c onn(): return get_connection. GOOD else: return get_connection. BAD_AUTH else: return get_connection. NO_SERVER get_connection. GOOD = 1 get_connection. BAD_AUTH = 2 get_connection. NO_SERVER = 3
Although in most cases this is probably okay, you're not guaranteed that
the name of your function will stay the same, so there are some hazards
in this style: def f(x):
.... return f.y * x
.... f.y = 100 f(2)
200 g, f = f, None g(2)
Traceback (most recent call last):
File "<interacti ve input>", line 1, in ?
File "<interacti ve input>", line 2, in f
AttributeError: 'NoneType' object has no attribute 'y'
One option is to turn your function into a class:
class get_connection( object):
GOOD = 1
BAD_AUTH = 2
NO_SERVER = 3
def __new__(cls):
if tcp_conn():
if server_allows_c onn():
return cls.GOOD
else:
return cls.BAD_AUTH
else:
return cls.NO_SERVER
This is a little sneaky here -- because you only need shared state
between all instances of get_connection, you don't actually ever need to
create an instance. So I've overridden __new__ to return the result of
the function instead. This allows you to call the function just like
you would have before. I haven't tested the code above, but here's a
simpler example that works:
class look_ma_no_func tion(object):
.... X = 42
.... def __new__(cls):
.... return cls.X
.... look_ma_no_func tion()
42
If you need to do this with a function that takes more parameters, you
can just add them to the __new__ declaration:
class look_ma_no_func tion(object):
.... X = 42
.... def __new__(cls, s):
.... return cls.X / float(len(s))
.... look_ma_no_func tion('answer to life the universe and everything')
1.0
Despite the fact that this particular use seems a little sneaky to me, I
do usually end up turning most functions that seem to need attributes
into classes (usually with a __call__ method defined).
Steve
george young wrote: [python 2.3.3, x86 linux] I recently found myself writing something like:
def get_connection( ): if tcp_conn(): if server_allows_c onn(): return 'good_conn' else: return 'bad_auth' else: return 'no_server'
cn = get_connection( ) if cn == 'good_con': ...
This is obviously just evil, since a misspelling in the string return is treacherous. I'm considering function attributes:
def get_connection( ): if tcp_conn(): if server_allows_c onn(): return get_connection. GOOD else: return get_connection. BAD_AUTH else: return get_connection. NO_SERVER get_connection. GOOD = 1 get_connection. BAD_AUTH = 2 get_connection. NO_SERVER = 3
If I put this function in it's own module, the solution is obvious:
GOOD_CONN = 1 def get_connection( ): ... return GOOD_CONN
But if this is a small utility function that belongs inside a larger module/class, I would like to have it's return values closely associated with the function, not just another value in the parent class.
Sorry, I also meant to add that the other obvious way of dealing with
this kind of thing is to make the results keyword parameters:
def get_connection( GOOD=1, BAD_AUTH=2, NO_SERVER=3):
if tcp_conn():
if server_allows_c onn():
return GOOD
else:
return BAD_AUTH
else:
return NO_SERVER
This has the benefit that if your user wants different return values
they can specify them, but the disadvantage that someone improperly
calling the function with more than 0 parameters will get, instead of an
error message, a strange return value.
Steve
Steven Bethard wrote: Sorry, I also meant to add that the other obvious way of dealing with this kind of thing is to make the results keyword parameters:
def get_connection( GOOD=1, BAD_AUTH=2, NO_SERVER=3): if tcp_conn(): if server_allows_c onn(): return GOOD else: return BAD_AUTH else: return NO_SERVER
This has the benefit that if your user wants different return values they can specify them, but the disadvantage that someone improperly calling the function with more than 0 parameters will get, instead of an error message, a strange return value.
Another disadvantage is that one must compare the return value by value
and not by name. That is, I cannot do something like this:
code = get_connection( )
if code == NO_SERVER:
...
--
Robert Kern rk***@ucsd.edu
"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter
Robert Kern wrote: Steven Bethard wrote:
Sorry, I also meant to add that the other obvious way of dealing with this kind of thing is to make the results keyword parameters:
def get_connection( GOOD=1, BAD_AUTH=2, NO_SERVER=3): if tcp_conn(): if server_allows_c onn(): return GOOD else: return BAD_AUTH else: return NO_SERVER
This has the benefit that if your user wants different return values they can specify them, but the disadvantage that someone improperly calling the function with more than 0 parameters will get, instead of an error message, a strange return value.
Another disadvantage is that one must compare the return value by value and not by name. That is, I cannot do something like this:
code = get_connection( ) if code == NO_SERVER: ...
Good point. The class-type implementation does allow you to do this: class get_connection( object):
.... GOOD = 1
.... BAD_AUTH = 2
.... NO_SERVER = 3
.... def __new__(cls):
.... if tcp_conn():
.... if server_allows_c onn():
.... return cls.GOOD
.... else:
.... return cls.BAD_AUTH
.... else:
.... return cls.NO_SERVER
.... get_connection. GOOD
1 get_connection. BAD_AUTH
2 get_connection. NO_SERVER
3
Steve
Hi George,
[george young Fri, Dec 10, 2004 at 10:45:47AM -0500] [python 2.3.3, x86 linux] I recently found myself writing something like:
def get_connection( ): if tcp_conn(): if server_allows_c onn(): return 'good_conn' else: return 'bad_auth' else: return 'no_server'
cn = get_connection( ) if cn == 'good_con': ...
This is obviously just evil, since a misspelling in the string return is treacherous.
Right.
I usually like to look at such problems from the angle of
what is most convenient for the *caller* side?
And having to adress function attributes does
not seem convenient. I'd probably like to do from
the caller side something like:
conn = get_connection( )
if conn.good:
...
elif conn.badauth:
...
elif conn.noserver:
...
which allows you to freely choose and hide your actual
implementation at the "called" side. Example:
class Connection(obje ct):
def __init__(self, **kw):
for name in kw:
assert name in ('good', 'badauth', 'noserver'), name
setattr(self, name, kw[name])
def get_connection( ):
if tcp_conn():
if server_allows_c onn():
return Connection(good =True)
else:
return Connection(bada uth=True)
else:
return Connection(nose rver=True)
And btw, the view of "what do i want at the caller side?"
is natural if you do test-driven development and actually
first write your tests. Another reason why testing is
a good thing :-)
cheers & HTH,
holger
On Fri, 10 Dec 2004 16:40:25 GMT
Steven Bethard <st************ @gmail.com> threw this fish to the penguins: george young wrote: This is obviously just evil, since a misspelling in the string return is treacherous. I'm considering function attributes:
def get_connection( ): if tcp_conn(): if server_allows_c onn(): return get_connection. GOOD else: return get_connection. BAD_AUTH else: return get_connection. NO_SERVER get_connection. GOOD = 1 get_connection. BAD_AUTH = 2 get_connection. NO_SERVER = 3 Although in most cases this is probably okay, you're not guaranteed that the name of your function will stay the same, so there are some hazards in this style:
>>> def f(x): ... return f.y * x ... >>> f.y = 100 >>> f(2) 200 >>> g, f = f, None >>> g(2) Traceback (most recent call last): File "<interacti ve input>", line 1, in ? File "<interacti ve input>", line 2, in f AttributeError: 'NoneType' object has no attribute 'y'
Yes, I was worried about this.
One option is to turn your function into a class:
class get_connection( object): GOOD = 1 BAD_AUTH = 2 NO_SERVER = 3 def __new__(cls): if tcp_conn(): if server_allows_c onn(): return cls.GOOD else: return cls.BAD_AUTH else: return cls.NO_SERVER
This is a little sneaky here -- because you only need shared state between all instances of get_connection, you don't actually ever need to create an instance. So I've overridden __new__ to return the result of the function instead. This allows you to call the function just like you would have before. I haven't tested the code above, but here's a simpler example that works: >>> class look_ma_no_func tion(object): ... X = 42 ... def __new__(cls): ... return cls.X ... >>> look_ma_no_func tion()
42
Hmm, this is quite clever, and indeed does what I want.
I hesitate to adopt it, though, because it *looks* sneaky.
For readable and maintainable code, I think it may be a bit
too hackish... The original impetus for my post was to find
a clear, maintainable form.
I wonder about returning an object that tests True if all is
ok, and has boolean attributes to query if not True...:
def get_connection( ):
class Ret:
def __init__(self, badauth=False, noserver=False) :
self.badauth = badauth
self.noserver = noserver
def __nonzero__(sel f):
return not(self.badaut h and self.noserver)
if tcp_conn():
if server_allows_c onn():
return Ret()
else:
return Ret(badauth=Tru e)
else:
return Ret(noserver=Tr ue)
ret = get_connection( )
if not ret:
if ret.badauth:
...
still seems a bit cumbersome in definition,
though the use is not bad...
-- George
--
"Are the gods not just?" "Oh no, child.
What would become of us if they were?" (CSL)
holger krekel wrote: Hi George,
[george young Fri, Dec 10, 2004 at 10:45:47AM -0500] [python 2.3.3, x86 linux] I recently found myself writing something like:
def get_connection( ): if tcp_conn(): if server_allows_c onn(): return 'good_conn' else: return 'bad_auth' else: return 'no_server'
cn = get_connection( ) if cn == 'good_con': ...
This is obviously just evil, since a misspelling in the string return is treacherous.
Right.
I usually like to look at such problems from the angle of what is most convenient for the *caller* side?
And having to adress function attributes does not seem convenient. I'd probably like to do from the caller side something like:
conn = get_connection( ) if conn.good: ... elif conn.badauth: ... elif conn.noserver: ...
which allows you to freely choose and hide your actual implementation at the "called" side. Example:
class Connection(obje ct): def __init__(self, **kw): for name in kw: assert name in ('good', 'badauth', 'noserver'), name setattr(self, name, kw[name])
def get_connection( ): if tcp_conn(): if server_allows_c onn(): return Connection(good =True) else: return Connection(bada uth=True) else: return Connection(nose rver=True)
That's evil, because "if conn.good" raises an AttributeError instead of
evaluating to False if the connection is not good. You would have to
inizialize all three attributes in every construction of a Connection
object.
Reinhold
--
[Windows ist wie] die Bahn: Man muss sich um nichts kuemmern, zahlt fuer
jede Kleinigkeit einen Aufpreis, der Service ist mies, Fremde koennen
jederzeit einsteigen, es ist unflexibel und zu allen anderen Verkehrs-
mitteln inkompatibel. -- Florian Diesch in dcoulm
[Reinhold Birkenfeld Fri, Dec 10, 2004 at 08:42:10PM +0100] holger krekel wrote: class Connection(obje ct): def __init__(self, **kw): for name in kw: assert name in ('good', 'badauth', 'noserver'), name setattr(self, name, kw[name])
def get_connection( ): if tcp_conn(): if server_allows_c onn(): return Connection(good =True) else: return Connection(bada uth=True) else: return Connection(nose rver=True)
That's evil, because "if conn.good" raises an AttributeError instead of evaluating to False if the connection is not good. You would have to inizialize all three attributes in every construction of a Connection object.
Ups, you are right of course. I somehow managed to delete the line ...
class Connection(obje ct):
good = badauth = noserver = False
thanks for pointing it out.
holger This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: David MacQuigg |
last post by:
I have what looks like a bug trying to generate new style classes with
a factory function.
class Animal(object): pass
class Mammal(Animal): pass
def newAnimal(bases=(Animal,), dict={}):
class C(object): pass
C.__bases__ = bases
dict = 0
|
by: Nobody |
last post by:
Lets say I have a class that is only available if a specific DLL (a.dll) is
present. I can't link to that DLL through lib files or my app will fail on
any machine that doesn't have a.dll.
So I do LoadLibrary()'s and keep function pointers in my wrapper class...
Which is a better style?
DWORD CClass::SomeFunc()
{
if (m_pfn != NULL)
|
by: pamelafluente |
last post by:
Hi guys,
Is it possible to add "onload" (via Javascript) a new class to the
<styleheader section?
If yes, how would that be done ?
<style type="text/css" media="screen">
.NewStyleClass{ whatever }
</style>
|
by: pamelafluente |
last post by:
Hi,
this time I am trying to add a style on the fly.I wish equivalency with
this one (only the menuItemStyle line):
<head>
<style type="text/css" media="screen">
... some static styles ...
..menuItemStyle{
background:#ddeeff;border-width:1px;border-style:inset;font-family:Arial;font-size:11px
|
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...
| |
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,...
|
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...
|
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,...
|
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...
|
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...
|
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
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
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...
| |