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

check type when assignment

Hello everyone:

Is there a way to check the type when do assignment?

if I write:
ab = bc
and want to make sure the return value of isinstance(bc, klass) is True
or I will raise
a exception.

Any suggestion?

Jul 12 '06 #1
4 3130
pipehappy <pipehappy <atgmail.comwrites:
>
Hello everyone:

Is there a way to check the type when do assignment?

if I write:
ab = bc
and want to make sure the return value of isinstance(bc, klass) is True
or I will raise
a exception.

Any suggestion?
1. Check your condition before the assignment: (IMO one-liners are over-rated)

if not isinstance(bc, klass):
raise TypeError # or do whatever else is appropriate
ab = bc

2. If you really insist on doing this in a single statement (in the assignment
itself), write a function for it:

def assert_type(obj, klass):
if not isinstance(bc, klass):
raise TypeError
return obj
ab = assert_type(bc, klass)

Or to be more generic:

def assert_return(obj, func):
assert func(obj)
return obj

ab = assert_return(bc, lambda obj:isinstance(obj, klass))

- Tal

Jul 12 '06 #2
pipehappy wrote:
Hello everyone:

Is there a way to check the type when do assignment?

if I write:
ab = bc
and want to make sure the return value of isinstance(bc, klass) is True
or I will raise
a exception.
In general, not doable. The assignment operator is not overloadable.

Only if you use assignments of the form

a.foo = bar

you could overwrite the __setattribute__-method to achieve what you want.
Diez
Jul 12 '06 #3
Diez B. Roggisch wrote:
pipehappy wrote:

>>Hello everyone:

Is there a way to check the type when do assignment?

if I write:
ab = bc
and want to make sure the return value of isinstance(bc, klass) is True
or I will raise
a exception.


In general, not doable. The assignment operator is not overloadable.

Only if you use assignments of the form

a.foo = bar

you could overwrite the __setattribute__-method
(Or use a Descriptor)
to achieve what you want.
>
Diez

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Jul 12 '06 #4
pipe,

In general it is not possible in one line. You have to do it before
hand or after with an if statement.

As a sidenote though you probably shouldn't use isinstance(), you might
need it less than you think you do, especially if you are using it to
check for some interface. For example, do you really care if bc is of
_type_ klass or just that bc just implements method x, y, z and has
arguments a, b,c? The two things seem to be the same, because they are
the same in C++ or Java, but they are not the same in Python. In Python
an interface and type inheritance can be orthogonal to each other. One
could add methods to objects or change them at will after
instantication such that the type hierarchy would be preserved but the
interface would be broken, or alternatively you could have an object of
a different type that fully implements the interface and could easily
be used in the code but just because it doesn't pass the isinstance()
test it is flagged as un-usable.
So in your code you could just test for the interface (methods and/or
attributes) with hasattr(bc, 'method') or even better just call the
method and see what happens, if it doesn't exist it will raise an
exception.

A much better explanation about the use and abuse of isinstance() is
here:
http://www.canonical.org/~kragen/isinstance/

Hope this helps,
Nick V.

pipehappy wrote:
Hello everyone:

Is there a way to check the type when do assignment?

if I write:
ab = bc
and want to make sure the return value of isinstance(bc, klass) is True
or I will raise
a exception.

Any suggestion?
Jul 12 '06 #5

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

Similar topics

18
by: Brian Genisio | last post by:
I know I have done this in Java, but is there a way to do it in C++? Type B and C inherit from type A. In a function, I want to check an instance of A (which can also be B or C), to see what...
5
by: tthunder | last post by:
Hi @all, Perhaps some of you know my problem, but I had to start a new thread. The old one started to become very very confusing. Here clean code (which compiles well with my BCB 6.0 compiler)....
5
by: Steve Wylie | last post by:
I am constructing an HTML questionnaire and one of the questions requires people to rate some choices from 1 to 5, where 1 is their favourite and 5 is their least favourite: Car Bus Taxi cab...
10
by: Bob | last post by:
This has been bugging me for a while now. GetType isn't availble for variables decalred as interface types, I have to DirectCast(somevariable, Object). In example: Sub SomeSub(ByVal...
669
by: Xah Lee | last post by:
in March, i posted a essay “What is Expressiveness in a Computer Language”, archived at: http://xahlee.org/perl-python/what_is_expresiveness.html I was informed then that there is a academic...
2
by: Rickard | last post by:
I want to dynamically check if I can assign from type A to type B in runtime. Type.IsAssignableFrom does not work for me as, typeof(int).IsAssignableFrom(typeof(short)) returns false, which is...
18
by: Joel Hedlund | last post by:
Hi! The question of type checking/enforcing has bothered me for a while, and since this newsgroup has a wealth of competence subscribed to it, I figured this would be a great way of learning...
34
by: Chris | last post by:
Is there ever a reason to declare this as if(*this == rhs) as opposed to what I normally see if(this == &rhs) ?
33
by: Ney Andr de Mello Zunino | last post by:
Hello. I have written a simple reference-counting smart pointer class template called RefCountPtr<T>. It works in conjunction with another class, ReferenceCountable, which is responsible for the...
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: 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...
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
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...
0
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...
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 projectplanning, coding, testing,...

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.