the annoying, verbose self

M

MonkeeSage

If you want to have a little fun:

class peverse:
def __call__(self):
raise AttributeError ("peverse instance has no __call__ method")

x = peverse()
x()

That is "peverse", but still...

from types import FunctionType
type(x) == FunctionType # False

And you can't (easily?) subclass FunctionType:

Error when calling the metaclass bases
type 'function' is not an acceptable base type

;)

Regards,
Jordan
 
B

Bruno Desthuilliers

Colin J. Williams a écrit :
Bruno Desthuilliers wrote:
[snip]>
Too bad : in Python, everything's an object, so 'methods' are
attributes too.

What do you see as a problem here?

You snipped too much... Tony wrote "However, I was more thinking in
terms of attributes only" (implying: attributes != methods). So the "too
bad" meant "won't work here".
> Surely it gives useful flexibility.

Indeed. But that's not the problem here.
 
B

Bruno Desthuilliers

MonkeeSage a écrit :
print callable(x)
=> True
That is "peverse", but still...

from types import FunctionType
type(x) == FunctionType # False

And you can't (easily?) subclass FunctionType:

Error when calling the metaclass bases
type 'function' is not an acceptable base type

;)

You don't have to subclass function to define a callable type that
implements the descriptor protocol so it behaves just like a function in
the context of an attribute lookup.
 
M

MonkeeSage

On Nov 27, 4:22 am, Bruno Desthuilliers
You don't have to subclass function to define a callable type that
implements the descriptor protocol so it behaves just like a function in
the context of an attribute lookup.

I'm aware, and I understand that python's types (as with other duck-
typed languages) are basically just an object's capabilities; I was
just pointing out that, if needed (though I can't think of why
offhand...mabye some kind of sandbox?), you can detect built-in
functions. Hmm...but then again, it seems that shadowing a built-in
function still reports as it's type as FunctionType...

In [1]: from types import FunctionType

In [2]: def len(x):
...: # mischief
...: pass
...:

In [3]: type(len) == FunctionType
Out[3]: True

Regards,
Jordan
 
I

Iain King

Bruno Desthuilliers <[email protected]>



wrote:



If you want to have a little fun:

class peverse:
def __call__(self):
raise AttributeError ("peverse instance has no __call__ method")

x = peverse()
x()


Horrific cluge:
--

def noself(func):
def t(*args, **kwargs):
self = args[0]
g = globals()
delete = []
for varname in dir(self):
if not varname.startswith("__") and varname not in g:
g[varname] = self.__getattribute__(varname)
delete.append(varname)
func(*args, **kwargs)
for varname in delete:
del(g[varname])
return t


class Test(object):
x = 1

@noself
def test(self):
print x

1

--

FTR, I won't be using this :) I do like this syntax though:

class Vector:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def abs(self):
using self:
return math.sqrt(.x*.x + .y*.y + .z*.z)

Iain
 
B

Bruno Desthuilliers

MonkeeSage a écrit :
On Nov 27, 4:22 am, Bruno Desthuilliers


I'm aware, and I understand that python's types (as with other duck-
typed languages) are basically just an object's capabilities; I was
just pointing out that, if needed (though I can't think of why
offhand...mabye some kind of sandbox?), you can detect built-in
functions.
Ok.

Hmm...but then again, it seems that shadowing a built-in
function still reports as it's type as FunctionType...

Of course (at least as long as you sahdow it with another function) -
Why would it be otherwise ?
 
D

Duncan Booth

Iain King said:
FTR, I won't be using this :) I do like this syntax though:

class Vector:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def abs(self):
using self:
return math.sqrt(.x*.x + .y*.y + .z*.z)

It is a bit verbose though. This variant is shorter on my system[*]:

class Vector:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def abs(self):
return math.sqrt(self.x*self.x + self.y*self.y + self.z*self.z)

[*] Windows, they are the same length on Linux.

:)
 
I

Iain King

Iain King said:
FTR, I won't be using this :) I do like this syntax though:
class Vector:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def abs(self):
using self:
return math.sqrt(.x*.x + .y*.y + .z*.z)

It is a bit verbose though. This variant is shorter on my system[*]:

class Vector:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def abs(self):
return math.sqrt(self.x*self.x + self.y*self.y + self.z*self.z)

[*] Windows, they are the same length on Linux.

:)

Yeah, in this example. Another would be

using NetworkConnection:
.address = "127.0.0.1"
.port = "8080"
.connect()
using .connection
while .read():
do something
.disconnect()

I doubt anything like this will take though, since you can write
similar code with 'with' and assigning a long name to a short one.

Iain
 
N

Neil Cerutti

Patrick Mullen a écrit :
(snip)
Still an unnecessary lookup on tmp though :) And it would be useless
to use it for one assignment, the idea is to eliminate all the typing
with this:

self.var1 = 5
self.var2 = "a value"
self.var3 = stuff
self.var4 = [2,54,7,7]
self.var5 = "dingaling"
self.var6 = 6.4
self.var7 = 1
self.var8 = False
self.var9 = True

self.__dict__.update(dict(var1=5, var2="a value", var3 = stuff, <etc>))

Someone else ? Or are we done with this DeadHorse ?

I was really upset about having to type 'self' all the time,
until I learned that in ABC, one of Python's precursors, you had
to use '__anInstanceOf_This_TYPE_or_Maybe_A__SubClassOfItInstead_arg0_'.
 
S

Steven D'Aprano

Fine. Now since Python let you define your own callable types and your
own descriptors, you can as well have an attribute that behave just like
a method without being an instance of any of the method types - so the
above test defeats duck typing. And since you can have callable
attributes that are definitively not methods, you can't rely on the fact
that an attribute is callable neither.

I did say the usual way was to call it and see what happens :)

(In Python3, I understand that is what callable() will do. Let's hope
that the function called has no side-effects.)

I also didn't mention classmethods, staticmethods or functions assigned
to attributes. As Ton van Vliet is a beginner, I didn't think he needed
to be flooded with too many complications all at once. It's quite
possible to program in Python for years and never come across a callable
attribute that isn't an ordinary method.

Also, I wasn't actually thinking about testing for methods before calling
them. Given the context, I was thinking more about manual experimentation
at the interpreter. Perhaps I should have said.
 
B

Bruno Desthuilliers

Steven D'Aprano a écrit :
I did say the usual way was to call it and see what happens :)

It's certainly *not* "the usual way" to test if some object is callable
- it's only ok if you really intented to call it, and even then it might
be better to test before calling so you distinguish exceptions raised
from within the called code from exceptions due the the call itself.
(In Python3, I understand that is what callable() will do.

IIRC, there's no callable() function at all in Python 3.
I also didn't mention classmethods, staticmethods or functions assigned
to attributes. As Ton van Vliet is a beginner, I didn't think he needed
to be flooded with too many complications all at once.

Understanding the object model of a (mostly) OO langage is not what I'd
call "too many complications". But I may be a bit biased !-)
It's quite
possible to program in Python for years and never come across a callable
attribute that isn't an ordinary method.

You loose !-)

callable(object.__class__)
=> True
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,165
Latest member
JavierBrak
Top