Python equivalents to MATLAB str2func, func2str, ischar, isfunc?

A

Alexander Schmolck

dmitrey said:
I can't find these via web serch

thank you in advance,
Dmitrey


str2func: getattr(some_module, 'f')
func2str: f.__name__
ischar: isinstance(x, basestring) and len(x) == 1
isfunc: callable(x) # is most likely to be what you want

'as
 
T

Travis Oliphant

dmitrey said:
I can't find these via web serch

You won't find exact equivalents. But, the same functionality is
available. Perhaps you would like to show us what you are trying to do
in Python.

Python's eval has some similarity with str2func

Python's repr() or str() has some similarity with func2str

ischar(A) is similiar to isinstance(A, str)

isfunc is similiar to callable

-Travis

P.S. (if you are using NumPy, then there are other possibilities as well.
 
D

dmitrey

Thank you
(however in MATLAB ischar is the same as isstr)
but what if I don't know the name of module?
I.e. I have

def myfunc(param): ...
#where param can be both funcName or a function, and I want to obtain
both name and func, something like
if isinstance(param, basestring):
func, funcName = <something>, param
else: func, funcName = param, param.__name__
what should I type instead of <something>?

D.
 
A

Alexander Schmolck

dmitrey said:
Thank you
(however in MATLAB ischar is the same as isstr)

Right, sorry.
but what if I don't know the name of module?
I.e. I have

def myfunc(param): ...
#where param can be both funcName or a function, and I want to obtain
both name and func, something like
if isinstance(param, basestring):
func, funcName = <something>, param
else: func, funcName = param, param.__name__
what should I type instead of <something>?

globals()[param] (I assume you don't want a local function, should one exist?)

'as
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,567
Members
45,042
Latest member
icassiem

Latest Threads

Top