Dumb python questions

Alex Martelli aleaxit at yahoo.com
Wed Aug 15 04:12:47 EDT 2001


"Paul Rubin" <phr-n2001 at nightsong.com> wrote in message
news:7xd75xlv86.fsf at ruckus.brouhaha.com...
> I just started playing with python and haven't been able to figure
> out the following things from the docs I've found:
>
> 1) Suppose I have a complex number like a = 3+4j.  How do I get the
> real and imaginary parts separately?  I guess I could say
>    x = (a + a.conjugate())/2
>    y = (a - a.conjugate())/2
> but I can't take this language seriously if that's what the designers
intended.

The a.real and a.imag read-only attributes of a are what you're looking for.


> 2) Is there a way I can tell if a value is of an integer type?  That is,
>    I want to write a function is_int(x) so that
>      is_int(3) = 1    # 3 is an integer type
>      is_int(3L) = 1   # 3L is an integer type
>      is_int(3.0) = 0  # 3.0 is float type
>      is_int(3+2j) = 0 # 3+2j is complex type

There are several approaches you can take for this.  type(x) returns
the type object for x, and you could compare that for equality with
type(1) or type(1L), but this is probably the worst approach.  The
builtin function isinstance(x,type(1)) currently has the same results
as the typetest type(x)==type(1) but should work better in the
future when it becomes possible to inherit from all builtin types.

With the current behavior of division,

def isinteger(x):
    return 0==x/(x+x)

would work, as integer division truncates, but that's slated to
change so I wouldn't rely on this.  (This would raise an exception
if x==0, too, so that would have to be tested separately).

See also the newly revised PEP on long/integer unification:
http://python.sourceforge.net/peps/pep-0237.html
eventually, isinstance(i, integer) should do exactly what you
ask for, but I get the impression it won't be in 2.2 yet.


> 3) Are the complex math functions specified to have any particular
>    branch cuts?  If they're unspecified, what happens in the actual cmath
>    implementation?  If they're unspecified, I'd like to propose that the
>    Scheme/Common Lisp conventions be adopted in a future version.

Fully specified at
http://python.sourceforge.net/devel-docs/lib/module-cmath.html
for example:
acos(x)
Return the arc cosine of x. There are two branch cuts: One extends right
from 1 along the real axis to ?, continuous from below. The other extends
left from -1 along the real axis to -?, continuous from above.

and so on.


Alex






More information about the Python-list mailing list