check to see if a symbol in a string has a binding
Bengt Richter
bokr at oz.net
Thu Apr 17 12:54:06 EDT 2003
On 17 Apr 2003 04:22:01 -0700, Jinsong Zhao <zhaojs at yahoo.com> wrote:
>Sorry if the question is too simple. I want to see if the name inside
>the string has a binding and callable. For example,
>
>1. func_string="func"
>2. func_string="func_string"
>3. func_string="dir"
>
>So the in case 1, "func" does not have a binding; case 2 "func_string"
>has a binding but not callable; in case 3 "dir" has a binding and is
>callable. How do I proceed based on the content in func_string? This
>is rather baffling.
>
>Any suggestion? Thanks in advance.
>
Insufficient spec. "Has a binding" in what name space?
Here's a possibility, passing the usual suspect namespaces
(not tested beyond what you see below):
>>> def isCallable(s, *namespaces):
... if not namespaces: raise ValueError, 'need at least one name space arg'
... for ns in namespaces:
... v = ns.get(s)
... if v: return callable(v)
... return 0
...
>>> for fs in 'func func_string dir'.split():
... print '%s: %s' % (fs, ('no', 'yes')[isCallable(fs)])
...
Traceback (most recent call last):
File "<stdin>", line 2, in ?
File "<stdin>", line 2, in isCallable
ValueError: need at least one name space arg
Oops, well that part got tested ;-)
>>> for fs in 'func func_string dir'.split():
... print '%s: %s' % (fs, ('no', 'yes')[isCallable(fs,vars(),
... globals(), __builtins__.__dict__)])
...
func: no
func_string: no
dir: yes
Regards,
Bengt Richter
More information about the Python-list
mailing list