473,386 Members | 1,706 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,386 software developers and data experts.

Why is there no instancemethod builtin?

Why hello there ha ha.

I have got in the habit of testing the types of variables with
isinstance and the builtin type names instead of using the types
module, as was the style back around Python 2.1. That is, rather than

if type(x) == types.ListType:

I now do:

if isinstance(x, list):

It is my understanding that this is what people do nowadays. One
problem I have, though, is that not all type names are available as
builtins. Just looking through the types declared in types, the
following are builtins:

bool, buffer, complex, dict, file, float, list, long,
object, slice, str, tuple, type, unicode, xrange, NoneType,
NotImplementedType

And the following are not:

dictproxy, ellipsis, frame, function, instancemethod, module,
traceback, instancemethod, NoneType, NotImplementedType

So for any in the latter batch, I have to import types after all. I
assume the dividing line is whether the name is useful as a
constructor. Still, I feel there's some inconsistencies in the
usefulness of the new type system. Why do str and unicode derive from
basestring, while list and tuple are independent types? list and
tuple support most of the same operations... it seems like either they
should also have an abstract base class or str and unicode shouldn't,
because duck typing doesn't really require that.

It also seems like types may be on the way out, because I don't see
constants for set or frozenset.

I'm not sure I have a question here, just pointing out what I see as
some flaws in the new type system.
Jul 19 '05 #1
7 2109
John Reese wrote:
Why hello there ha ha. [snip]
Just looking through the types declared in types, the following are builtins:
[snip]
... NoneType,
NotImplementedType

And the following are not:
[snip]
... NoneType, NotImplementedType

So for any in the latter batch, I have to import types after all.


Plonk.
Jul 19 '05 #2
John Reese wrote:
I now do:

if isinstance(x, list):

It is my understanding that this is what people do nowadays.


I wouldn't go that far. I don't have an isinstance check for lists
anywhere in my entire codebase. Why do you think you need to check to
see if something is of type list? Why don't you just use it as needed,
and find out, e.g.:

try:
itr = iter(x)
except TypeError:
# do whatever you need to do if it's not iterable
else:
# do whatever you need to do if it *is* iterable

STeVe
Jul 19 '05 #3
On Fri, 17 Jun 2005 16:40:56 -0600, <st************@gmail.com> wrote:
John Reese wrote:
I now do:

if isinstance(x, list):

It is my understanding that this is what people do nowadays.


I wouldn't go that far. I don't have an isinstance check for lists
anywhere in my entire codebase. Why do you think you need to check to
see if something is of type list? Why don't you just use it as needed,
and find out, e.g.:

try:
itr = iter(x)
except TypeError:
# do whatever you need to do if it's not iterable
else:
# do whatever you need to do if it *is* iterable

STeVe


I'm not saying I do it a lot, but sometimes it's useful to write
methods with interfaces like, well, isinstance's, whose second argument
can be a single type object or a sequence of class objects. The
standard conditional vs. exception tradeoffs exist here... if it's
likely that x isn't iterable, I shouldn't have to incur the time and
heap churn penalty of filling in sys.exc_info and its obsolete
cousins, potentially rolling back the stack, etc.
Jul 19 '05 #4
John Reese wrote:
I now do:
if isinstance(x, list): [snip]
I'm not saying I do it a lot, but sometimes it's useful to write
methods with interfaces like, well, isinstance's, whose second argument
can be a single type object or a sequence of class objects.


Personally, I'd just write these functions with a *args instead, e.g.:

def my_isinstance(obj, *types):
return isinstance(obj, types)

Sure, it's not an option if you need multiple type lists, but how often
does that happen?

STeVe
Jul 19 '05 #5
"John Reese" <jt*@ofb.net> wrote in message
news:slrndb6ct5.pho.jt*@ofb.net...
Why hello there ha ha.

I have got in the habit of testing the types of variables with
isinstance and the builtin type names instead of using the types
module, as was the style back around Python 2.1. That is, rather than

if type(x) == types.ListType:

I now do:

if isinstance(x, list):
you need _both_ isinstance and the types module to do a correct
check for any string type: isinstance(fubar, types.StringTypes).
That's because both string and unicode are subtypes of one base.
It is my understanding that this is what people do nowadays. One
problem I have, though, is that not all type names are available as
builtins. Just looking through the types declared in types, the
following are builtins:

bool, buffer, complex, dict, file, float, list, long,
object, slice, str, tuple, type, unicode, xrange, NoneType,
NotImplementedType

And the following are not:

dictproxy, ellipsis, frame, function, instancemethod, module,
traceback, instancemethod, NoneType, NotImplementedType


You need to do your homework better. You have, for example
NoneType and NotImplementedType in both lists.

The basic answer to your question is that the types in builtins
are there because they have uses other than type checks.
Being useful for type checks is not the criterion for being in
builtins. That's the function of the types module.

The other point to be made here is that, in most cases,
type checks are a design smell. That's not always true, but
it's the first thing to check when you see one.

John Roth

Jul 19 '05 #6
"Steven Bethard" wrote:
John Reese wrote:
I now do:

if isinstance(x, list):

It is my understanding that this is what people do nowadays.


I wouldn't go that far. I don't have an isinstance check for lists
anywhere in my entire codebase. Why do you think you need to check to
see if something is of type list? Why don't you just use it as needed,
and find out, e.g.:

try:
itr = iter(x)
except TypeError:
# do whatever you need to do if it's not iterable
else:
# do whatever you need to do if it *is* iterable


A class of cases I've found necessary to do explicit type checking is
when a different action is taken for different types, but where duck
typing can't distinguish between them. For example, a function that
returns a string representation of an S-expression, represented as a
list of nested lists:

def s_expr(obj):
if isinstance(obj, list):
return "(%s)" % ' '.join(map(s_expr,obj))
else:
return str(obj)
s_expr([1, [2,3], [4,5], "foo"])
'(1 (2 3) (4 5) foo)'


Here duck typing doesn't help because the function should take the if
branch only for lists and not other iterables (e.g. strings).

George

Jul 19 '05 #7
[George Sakkis]
The fact that strings don't have __iter__ is an implementation
detail. I can't think of any reason other than historic and perhaps
backwards compatibility for this;
iterables should IMHO by definition be exactly
the objects with __iter__).
There would be no benefit other than satisfying that particular world
view. It is a feature that all sequences are automatically iterable
without having to write a custom __iter__ method. That makes life a
bit easier for writers of sequence-like classes.

[Michele Simionato] I think strings do not have __iter__ on purpose, exactly to
distinguish them from other iterables, since sometimes it is nice
to consider them atomic, but I am not sure of this. You should
ask the developers.
That is not correct. Since any sequence is automatically iterable
(because of the presence of __getitem__), the inclusion of a separate
__iter__ method is purely optional. The option to include a custom
__iter__ method has been exercised only when it has offered some
performance benefit. IOW, the inclusion of __iter__ for a sequence is
an arbitrary implementation detail -- there is no other significance.

Anyway, the right definition of iterable is
(as I was told) "an object X such that iter(X) does not throw an
exception". Objects following the __getitem__ protocol
- such as strings -are iterables even if they do not have
an __iter__ method.


An object is iterable if and only if it provides either __iter__ or
__getitem__.

Raymond

Jul 19 '05 #8

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

Similar topics

7
by: Rim | last post by:
Hi, It appears to me the simplest way to add a function to a class outside of the class declaration is as follows: >>> class a(object): .... pass .... >>> def f(self): .... print 'hi'
7
by: ‘5ÛHH575-UAZWKVVP-7H2H48V3 | last post by:
(see end of message for example code) When an instance has a dynamically assigned instance method, deepcopy throws a TypeError with the message "TypeError: instancemethod expected at least 2...
1
by: Martin Miller | last post by:
In section "3.27 new -- Creation of runtime internal objects" of the documentation that comes with Python 2.4 it says: > instancemethod(function, instance, class) > > This function will return...
4
by: bonono | last post by:
I came across this while searching for a way to DIY partial(), until it is available in 2.5 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/229472 However, when trying for the...
6
by: Anders K. Olsen | last post by:
Hello group I'm trying to list the users and groups who has read access to a file. I use .NET 2.0 and FileInfo.GetAccessControl().GetAccessRules(...) and then loop through the...
6
by: Jim Lewis | last post by:
Pickling an instance of a class, gives "can't pickle instancemethod objects". What does this mean? How do I find the class method creating the problem?
2
by: Steven Bethard | last post by:
I'd like to be able to pickle instancemethod objects mainly because I want to be able to delay a call like ``foo(spam, badger)`` by dumping ``foo``, ``spam`` and ``badger`` to disk and loading them...
11
by: Gert Cuykens | last post by:
import MySQLdb class Db: _db=-1 _cursor=-1 @classmethod def __init__(self,server,user,password,database): self._db=MySQLdb.connect(server , user , password , database)
2
by: Michele Simionato | last post by:
Can somebody explain what's happening with the following script? $ echo example.py import pickle class Example(object): def __init__(self, obj, registry): self._obj = obj self._registry =...
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: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
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...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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
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.