473,654 Members | 3,040 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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,
NotImplementedT ype

And the following are not:

dictproxy, ellipsis, frame, function, instancemethod, module,
traceback, instancemethod, NoneType, NotImplementedT ype

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 2122
John Reese wrote:
Why hello there ha ha. [snip]
Just looking through the types declared in types, the following are builtins:
[snip]
... NoneType,
NotImplementedT ype

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

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(o bj, *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.ne t...
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(fuba r, types.StringTyp es).
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,
NotImplementedT ype

And the following are not:

dictproxy, ellipsis, frame, function, instancemethod, module,
traceback, instancemethod, NoneType, NotImplementedT ype


You need to do your homework better. You have, for example
NoneType and NotImplementedT ype 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_ex pr,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
1799
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
3966
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 arguments, got 0". Tested with Python 2.3.4 on OpenBSD and Python 2.4 on Win98; same results. Is this a bug in deepcopy, how I dynamically assign the instance method or something else? (See example code for how I did it.) If you're curious as...
1
1855
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 a method object, bound to instance, or unbound if > instance is None. function must be callable. However, some simple experiments I've tried seem to indicate that the
4
1513
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 following, it doesn't work and is wondering if it is a bug or intended : >>> import operator >>> import new
6
5572
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 FileSystemAccessRule objects. Using these objects, it is easy to use rule.IdentityReference.Translate(typeof(NTAccount)) to get the NTAccount object. I have noticed that some of the NTAccounts can belong to BUILTIN domains,
6
12333
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
2137
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 again later. Sometimes the callable ``foo`` is actually a bound method, e.g. ``bar.baz``, but in such cases, pickle doesn't work by default because it doesn't know how to pickle/unpickle instancemethod objects. I was thinking of doing...
11
3376
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
3528
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 = registry
0
8375
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, 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...
0
8815
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
8707
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...
0
7306
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...
0
5622
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
4149
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4294
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2714
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
1593
bsmnconsultancy
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...

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.