I need to test an argument for a few different types.
I'm calling my function like this
arf = MyFunc(list)
What I want to do is to test for whether something is a string, tuple, list or
function. It's that last one that's causing me a problem.
if isinstance(arg, (str, tuple, list)):
No problem, but there are a lot of types that the type function returns. If I
have a simple function
def foo():
pass
type(foo)
prints out
<type 'function'>
So, my question is, what value can I use as the 2nd arg to isinstance to see if
foo is a function? And while I'm on the subject, what types does isinstance not
support?
And last, what is the correct way to do it if this is not the right way?
TIA (and hoping I'm clear)
--
Time flies like the wind. Fruit flies like a banana. Stranger things have .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
Does it have to be a function? -- There's quite a few things which are
function-y enough that you really should accept them even if they may
not be technically a /function/. Like a class instance with the __call__
method defined wrapping a function as a decorator. Or a bound method,
really.
In Python 2.x, you can use callable(fun) -- that goes away in Py3
though. But personally, I think this is the wrong approach.
I'm assuming you need to do some different sort of behavior based on if
its a str, tuple or list-- okay.
But, personally-- at that point, I would just *assume* the argument is a
function. And call it.
If it can't be called, its not a functiony-thing. You can either let
that traceback propagate, or just raise a TypeError "expected arg to be
a string, tuple, list or callable".
Then again, similarly I almost never want to test for if somethings a
tuple or list. I'd rather use it as a sequence type and see if it works:
while there's not as many 'sequency-like-things' out there as there are
function-like-things, there's still quite a few.
So personally, I'd check if its a string (can it be unicode or regular?
If so isinstance(x,basestring)).
Then I'd try to use it as a sequence, doing whatever I woulda done with
it sequence-like. If that works, great. If not, I'd try to call it.
Etc.
Then again it does depend on just what you're *doing* with the arg being
passed in.
--
... Stephen Hansen
... Also: Ixokai
... Mail: me+list/python (AT) ixokai (DOT) io
... Blog: http://meh.ixokai.io/
... pass
['BooleanType', 'BufferType', 'BuiltinFunctionType',
'BuiltinMethodType', 'ClassType', 'CodeType', 'ComplexType',
'DictProxyType', 'DictType', 'DictionaryType', 'EllipsisType',
'FileType', 'FloatType', 'FrameType', 'FunctionType', 'GeneratorType',
'GetSetDescriptorType', 'InstanceType', 'IntType', 'LambdaType',
'ListType', 'LongType', 'MemberDescriptorType', 'MethodType',
'ModuleType', 'NoneType', 'NotImplementedType', 'ObjectType',
'SliceType', 'StringType', 'StringTypes', 'TracebackType', 'TupleType',
'TypeType', 'UnboundMethodType', 'UnicodeType', 'XRangeType',
'__builtins__', '__doc__', '__file__', '__name__', '__package__']
Why do you want to know what type it is? Do you want to do different
things depending on the type? If the same function can return instances
of any number of unrelated types/classes, then there's something wrong
in your design! (You should also learn what "duck typing" is!) :-)
Ok, you just asked great questions, and your questions were based on what I
didn't tell you.
I'm trying to teach myself about how __metaclass__ can be used as a substitute
for LSD. ;-)
So, instead of writing a class that does typechecking on its arguments at
instantiation time, I'm writing a metaclass that allows the class to announce
what sort of values it specifically will be expecting after instantiation.
The model I'm using is something I've found that
http://cleverdevil.org/computing/78/
So, the basic idea is
... name = Field(str)
... age = Field(int)
... ff = Field(function)
but there's no factory function called function.
Does this help?
--
Time flies like the wind. Fruit flies like a banana. Stranger things have .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
Ah. In that case, bearing in mind this won't work for Python 3, I would
use callable().
So, isinstance(x, (int, str, tuple)); but don't rely on isinstance for
function. Its just not appropriate, almost universally, to really be
that specific.
When someone esays they want to accept a function, what they *really*
mean in my experience is they want some sort of object that you can put
()'s on after, and usually with some sort of agreement: it'll accept X
args, and return Y things.
You can't readily test for those agreements, but you can test to see if
it'll accept ()'s after and be all function-y. Doing callable(ff) will
do that for you.
--
... Stephen Hansen
... Also: Ixokai
... Mail: me+list/python (AT) ixokai (DOT) io
... Blog: http://meh.ixokai.io/
P.S. The removal of callable is something I don't understand in Python
3: while generally speaking I do really believe and use duck typing, I
too have on occassion wanted to dispatch based on 'is callable? do x'.
Sometimes its not convenient to do so via duck typing. Its rare. But it
is there. That isinstance()/issubclass got a boost in power with the
ABC's and registering, while at the same time the ability to introspect
about the function-y callable-y ness of a function was removed? Makes no
sense to me. But alas!
There's always: isinstance(<object>, collections.Callable)
Why in Guido's name is that in the collections module of all places?
What hath callability to do with container objects?
Cheers,
Chris
--
http://blog.rebertia.com
What the hell? When did that show up? o.O (Did I not pay attention
enough during the ABC conversations? It seemed so boring).
A) how is Callable a collection, in any way shape or form? And B) does
that really return True for everything callable-esque? (I don't have a
3.x to play with on this temporary computer)
--
... Stephen Hansen
... Also: Ixokai
... Mail: me+list/python (AT) ixokai (DOT) io
... Blog: http://meh.ixokai.io/
It's Benevolent _Dictator_ For Life. Not Benevolent _Diety_ For Life.
Just because a man has an uncanny sense of style (in the programming
sense) and a time machine, doesn't a god make.
--
... Stephen Hansen
... Also: Ixokai
... Mail: me+list/python (AT) ixokai (DOT) io
... Blog: http://meh.ixokai.io/
The PEPs & post-release docs detailing Py3 changes were worth reading,
it's noted in the sections on changes to built-ins:
http://www.python.org/dev/peps/pep-3100/
http://docs.python.org/py3k/whatsnew/3.0.html
A) I was tempted to say "it's a collection of code" :) But really, the
role of the collections model has expanded in 3.x to also provide a
repository for ABCs:
"In addition to containers, the collections module provides some ABCs
(abstract base classes) that can be used to test whether a class
provides a particular interface, for example, whether it is hashable
or a mapping."
http://docs.python.org/py3k/library/collections.html
B) In a quick test in 3.1.2, it returned true for a function, a bound
and unbound lambda, and an instance of a class with a __call__
defined. If there's any other kind of callable you can think of, let
me know and I'll be happy to test it.
Completely agree, see my prior reply.
You don't even need 3.x; it was added in 2.6. The new magic of
__instancecheck__ makes it possible.
See http://docs.python.org/reference/datamodel.html#customizing-[..]
Cheers,
Chris
--
Very cool new magic, eh? http://blog.rebertia.com
-- http://mail.python.org/mailman/listinfo/python-list
I've actually read nearly all of that multiple times-- I tend to idly
re-read such things. But not everything sticks (as its usually late like
now and I'm multitasking and just exploring curiously). Callable in
collections (and the ABC's in collections-- I swear I thought they were
in a module of their own) totally didn't sink in.
The documentation might say something crazy, but just because its
*officially* crazy doesn't make it any less actually crazy.
Just because most of the ABC's are vaguely collection-related, doesn't
mean we should put them all into the collections module if there's some
which aren't really collection-ish. It argues for either putting
different ABC's in different places (say, Callable in functools? Who
knows) or just putting them all in a single module. I dunno which: its
far too late to do anything about now, but yeah.
Re-defining a module to suddenly include various random tidbits which
aren't even really related to that module's purpose counts as crazy in
my book.
I don't often think, "That's crazy." about Python, too. And although I'm
not really in a place to use Python 3 yet, I do try to learn more and
more of it as time goes on and play with it (and experiment with it) so
that when I'm able, I'll be ready. And so far I've been largely very
pleased, although Python 2 was rarely crazy (print >>crazy, "not
withstanding") I've been pleased with the less odd edges as I explore Py3.
Until now.
Oh well, nothing can be perfect. :)
--
... Stephen Hansen
... Also: Ixokai
... Mail: me+list/python (AT) ixokai (DOT) io
... Blog: http://meh.ixokai.io/
There's also: hasattr(<object>, '__call__'). It works in both 2.x and 3.x.
-- HansM
Good work, Hans. I do find that to be a more pythonic approach,
personally, being more concerned with an object's ability than its
abstract type.
--
http://mail.python.org/mailman/listinfo/python-list