Best practice to write generic numerical functions that work with both ndarray and MaskedArray

谁说胖子不能爱 提交于 2019-12-07 17:20:35

问题


Is there a more beautiful way than:

import numpy as np
from numpy import ma
def foo(x):
    pkg = ma if isinstance(x, ma.MaskedArray) else np
    return pkg.apply_along_axis(bar, -1, x)

I feel it not Pythonic, in terms of trying to make the most out of polymorphism.

EDIT

The above code snippet is just a demo to highlight the fact that np and ma have highly similar (designed on purpose) interface (e.g., apply_along_axis), but under different namespace.


回答1:


isinstance() is fine as it is here.

You could make it implicit if you'd like using a single-dispatch generic function:

from pkgutil import simplegeneric

import numpy as np
from numpy import ma

@simplegeneric
def pkg(obj):
    return np # use numpy by default

@pkg.register(ma.MaskedArray)
def _(x):
    return ma

def foo(x):
    return pkg(x).apply_along_axis(bar, -1, x)

Here's another example of generic function in Python.



来源:https://stackoverflow.com/questions/20771788/best-practice-to-write-generic-numerical-functions-that-work-with-both-ndarray-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!