473,399 Members | 2,774 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,399 software developers and data experts.

An Object's Type

Hi,

Is it possible to find out if an object is of a certain type or of a
type derived from this type?

Thanks,

Barry
Dec 5 '07 #1
9 1801
bg***@yahoo.com wrote:
Hi,

Is it possible to find out if an object is of a certain type or of a
type derived from this type?
http://docs.python.org/lib/built-in-funcs.html

Look for isinstance.

Diez
Dec 5 '07 #2
bg***@yahoo.com wrote:
Hi,

Is it possible to find out if an object is of a certain type or of a
type derived from this type?
class Example(object):
pass

class AnotherExample(Example):
pass
>>issubclass(Example, object)
True
>>issubclass(AnotherExample, object)
True
>>issubclass(AnotherExample, Example)
True
>>issubclass(Example, AnotherExample)
False

And finally
>>isinstance(Example, type)
True

This is true because type is the metaclass of object. Though you don't
have to understand it. ;)
Christian

Dec 5 '07 #3
bg***@yahoo.com a écrit :
Hi,

Is it possible to find out if an object is of a certain type or of a
type derived from this type?
You have the answer, thanks to Diez and Christian. Now unless you have a
*very* compelling reason to check the type of an object, *just forget
about it*. 9 times out of 10, this is fighting against the language's
type system (hint: google for "duck typing").

Dec 5 '07 #4
Bruno Desthuilliers schrieb:
bg***@yahoo.com a écrit :
>Hi,

Is it possible to find out if an object is of a certain type or of a
type derived from this type?
You have the answer, thanks to Diez and Christian. Now unless you have a
*very* compelling reason to check the type of an object, *just forget
about it*. 9 times out of 10, this is fighting against the language's
type system (hint: google for "duck typing").
So I have to give up the concept that argument types are part of the
interface or signature? Honestly, I don't like that. Granted; not having
strict type checking makes for great flexibility but the price is you
either write typchecking code or let the error propagate into the
function or method. I hope type annotations in py3k will allow for
something like constraints in C# where you can tell the caller right
away she's doing something wrong.

greetings
Paul

BTW: are type annotations to be backported to 2.x?

Dec 6 '07 #5
paul schrieb:
Bruno Desthuilliers schrieb:
>bg***@yahoo.com a écrit :
>>Hi,

Is it possible to find out if an object is of a certain type or of a
type derived from this type?
You have the answer, thanks to Diez and Christian. Now unless you have
a *very* compelling reason to check the type of an object, *just
forget about it*. 9 times out of 10, this is fighting against the
language's type system (hint: google for "duck typing").
So I have to give up the concept that argument types are part of the
interface or signature? Honestly, I don't like that. Granted; not having
strict type checking makes for great flexibility but the price is you
either write typchecking code or let the error propagate into the
function or method. I hope type annotations in py3k will allow for
something like constraints in C# where you can tell the caller right
away she's doing something wrong.

This is a dead horse beaten into the ground, full way through to china.
If you want typechecking - use a statically checked language. After all,
if you like to constrain yourself to certain types - why not benefit
from a compiler then?

I for once prefer to be able to pass object that behaves like e.g. a
file - think StringIO - to something taking a file, instead of
introducing a interface-maze like the java.io-hierarchy to capture each
possible thinkable aspect of file IO in a separate interface - and then
hoping that the third party library was careful enough to only require
what is really needed.

Diez
Dec 6 '07 #6
paul a écrit :
Bruno Desthuilliers schrieb:
>bg***@yahoo.com a écrit :
>>Hi,

Is it possible to find out if an object is of a certain type or of a
type derived from this type?
You have the answer, thanks to Diez and Christian. Now unless you have
a *very* compelling reason to check the type of an object, *just
forget about it*. 9 times out of 10, this is fighting against the
language's type system (hint: google for "duck typing").
So I have to give up the concept that argument types are part of the
interface or signature?
Nope - you have to give up the notion of type you learned from
statically typed languages, and get used to the one used in dynamically
typed languages. Same word, different concept, really.
Honestly, I don't like that. Granted; not having
strict type checking makes for great flexibility but the price is you
either write typchecking code or let the error propagate into the
function or method.
Just tell me: what will happens if, *in Python*, you "write typechecking
code" ? Surely, when you'll (possibly wrongly[1]) conclude you don't
have the "correct" type (meaning: the one you expected when writing your
code[1]), you'll raise an exception, won't you ? (I can't imagine what
else...). So ask yourself: in which way will the final result be
different from would very probably happens without the "typecheking
code" ? In *both* cases, you end up with a runtime exception.

Granted, without "typechecking", there can be a couple corner cases
where you end up with incorrect results instead of an exception (like
your user passed a string where you expected a sequence which is *not* a
string). These corner cases might be worth the most minimal possible
check. As far as I'm concerned, I've run into this kind of corner case
perhaps half a dozen time in 7+ years. And usually because I (as a user
of someone else's code) failed to read the doc - which is my
responsability, the author's.
[1] dynamic typing means that two totally unrelated types may both
implement the expected (implied) interface. You just can't hope to know
by advance the exhaustive list of classes that will implement the
interface your code expects.
I hope type annotations in py3k will allow for
something like constraints in C# where you can tell the caller right
away she's doing something wrong.
Lord have mercy. As Diez mentions, if you want static type checking,
then don't use a dynamically typed language. But trying to fight against
the language is not going to buy you much.

Dec 6 '07 #7
Bruno Desthuilliers <br********************@wtf.websiteburo.oops.com >
writes:
So ask yourself: in which way will the final result be different
from would very probably happens without the "typecheking code" ? In
*both* cases, you end up with a runtime exception.
The idea behind such type checks is to make sure type errors are
caught as early as possible. Exceptions caught later, the philosophy
goes, are harder to debug because by then the cause of the problem can
be obscured. Consider an object of the wrong type passed to a method:
the method can store the object in its own instance attribute, and
keep working on something else. Then, much later, the faulty object
gets actually used and the error is raised. By the time the exception
is thrown, you have no idea where the offending object came from.

Personally, I consider the loss in flexibility to outweigh any
benefits of overeager type checks. Besides, type checks are only one
of the many possible constraints you could check in your objects, yet
proponents of type checks tend to treat them as somehow much more
important or fundamental.

Hopefully Python 3's support for abstract base classes will provide a
standard way to have our cake and eat it by allowing declarative
subtypes. That way type checks will be possible to prevent accidents,
but without compromising flexibility. Pure "duck typing" will be made
a bit more verbose, but not impossibly so.
Dec 6 '07 #8
Hrvoje Niksic a écrit :
Bruno Desthuilliers <br********************@wtf.websiteburo.oops.com >
writes:

>>So ask yourself: in which way will the final result be different
from would very probably happens without the "typecheking code" ? In
*both* cases, you end up with a runtime exception.

The idea behind such type checks is to make sure type errors are
caught as early as possible. Exceptions caught later, the philosophy
goes, are harder to debug because by then the cause of the problem can
be obscured. Consider an object of the wrong type passed to a method:
the method can store the object in its own instance attribute, and
keep working on something else. Then, much later, the faulty object
gets actually used and the error is raised. By the time the exception
is thrown, you have no idea where the offending object came from.
That's the theory, yes. In practice, when such a situation occurs, it's
usually easy to track down the problem: just add a temporary check in
the method (or around it - using a decorator), rerun the program and
you'll be done. Once the faulty code is corrected, remove the check.
Dec 6 '07 #9
Chris Mellon schrieb:
On Dec 6, 2007 5:52 AM, paul <pa**@subsignal.orgwrote:
>function or method. I hope type annotations in py3k will allow for
something like constraints in C# where you can tell the caller right
away she's doing something wrong.
[language rant snipped]
On a more pragmatic basis, there are only 2 kinds of type errors in Python:
1: The object passed doesn't implement the correct interface, and will
raise an error when called. This will be caught by a unit test.
2: The object passed implements something that looks like the right
interface, but implements it incorrectly. This will be caught by a
unit tests.
So if I use your code I need to read all of it to understand how "file
like" something for bla(filelike) needs to be to be able to write
unittests? Or do your unittests magically detect all possible callers
and send them email with nice warnings?
>
Note that both these errors will be caught by behavior exercising unit
tests and do not rely on any sort of "typechecking code" to be
written. Explicit typechecking in Python is done only when you need to
dispatch on type, not because you feel like generating spurious
errors.
Do you prefer situations like Hrvoje has descibed two post below?

To reiterate: I'd like to have a TypeError: "foo called with <str>,
<Pointexpected" which is concise and informative for the caller,
rather than have him hunt down obscure errors in totally unrelated code
like AttributeError: 'str' object has no attribute 'move'.

greetings
Paul

Dec 7 '07 #10

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

Similar topics

4
by: Avi Kak | last post by:
Hello: Please forgive me if my question is too silly or just not well-formed. Wesley Chun in his book (Core Python Programming) says that **everything** in Python is an object. So I became...
44
by: Steven T. Hatton | last post by:
This may seem like such a simple question, I should be embarrassed to ask it. The FAQ says an object is "A region of storage with associated semantics." OK, what exactly is meant by "associated...
16
by: sneill | last post by:
How is it possible to take the value of a variable (in this case, MODE_CREATE, MODE_UPDATE, etc) and use that as an object property name? In the following example I want 'oIcon' object to have...
100
by: E. Robert Tisdale | last post by:
What is an object? Where did this term come from? Does it have any relation to the objects in "object oriented programming"?
5
by: Matthew | last post by:
I have a nice little Sub that saves data in a class "mySettings" to an XML file. I call it like so: Dim mySettings As mySettings = New mySettings mySettings.value1 = "someText" mySettings.value2...
16
by: anonymous.user0 | last post by:
The way I understand it, if I have an object Listener that has registered as a listener for some event Event that's produced by an object Emitter, as long as Emitter is still allocated Listener...
26
by: yb | last post by:
Hi, Is there a standard for the global 'window' object in browsers? For example, it supports methods such as setInterval and clearInterval, and several others. I know that w3c standardized...
3
by: User1014 | last post by:
A global variable is really just a property of the "Global Object", so what does that make a function defined in the global context? A method of the Global Object? ...
2
by: Ralph | last post by:
Hi I don't understand why it's not working: function schedule(imTop){ this.tdImagesTop = imTop; } schedule.prototype.selectEl = function() { alert(this.tdImagesTop);
5
by: JH | last post by:
Hi I found that a type/class are both a subclass and a instance of base type "object". It conflicts to my understanding that: 1.) a type/class object is created from class statement 2.) a...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
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
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
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
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
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,...
0
isladogs
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...

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.