小编bou*_*n21的帖子

如何使用 TypeVar 键入 __iter__ ?

我正在尝试创建一个具有通用类型的数据类,我可以将其解压并作为 numpy 的 linspace 的参数提供。__iter__为此,我需要使用 TypeVar给出返回类型:

from typing import Iterator, Union, Generic, TypeVar, Any
import numpy as np

VT = TypeVar("VT", bound=float)

class Arguments(Generic[VT]):
    def __init__(self, start: VT, stop: VT, num: int):
        self.start = start
        self.stop = stop
        self.num = num

    def __iter__(self) -> Iterator[Union[VT, int]]:
        return iter([self.start, self.stop, self.num])

args: Arguments[float] = Arguments(1.2, 2.5, 10)

print(np.linspace(*args))
Run Code Online (Sandbox Code Playgroud)

执行工作正常,但 mypy (0.920) 失败并出现以下错误:

$ mypy test.py
test.py:17: error: No overload variant of "linspace" matches argument type "Arguments[float]"  [call-overload]
test.py:17: note: …
Run Code Online (Sandbox Code Playgroud)

python mypy python-typing

5
推荐指数
1
解决办法
656
查看次数

传递所有当前变量以在python中运行

我想在Python中调用一个函数,允许我在执行期间访问所有当前变量(用于调试).像这样的东西:

def interruptWithTerminal():
    interruptchoice = ""
    while interruptchoice != "Y":
        interruptchoice = raw_input("print what variable? (Y to continue script): ")
        try:
            print eval(interruptchoice)
        except:
            print "Error"
Run Code Online (Sandbox Code Playgroud)

我的问题是我在调用此函数时无法访问变量.有任何想法吗?

python debugging function parameter-passing

1
推荐指数
1
解决办法
179
查看次数

是否有内置的方法或函数来映射numpy.ndarray上的函数?

我想将一个函数应用于a的每个元素numpy.ndarray,如下所示:

import numpy
import math

a = numpy.arange(10).reshape(2,5)
b = map(math.sin, a)
print b
Run Code Online (Sandbox Code Playgroud)

但这给了:

TypeError: only length-1 arrays can be converted to Python scalars
Run Code Online (Sandbox Code Playgroud)

我知道我可以这样做:

import numpy
import math
a = numpy.arange(10).reshape(2,5)

def recursive_map(function, value):
    if isinstance(value, (list, numpy.ndarray)):
        out = numpy.array(map(lambda x: recursive_map(function, x), value))
    else:
        out = function(value)
    return out
c = recursive_map(math.sin, a)
print c
Run Code Online (Sandbox Code Playgroud)

我的问题是:是否有内置函数或方法来执行此操作?它似乎很简单,但我找不到它.我在用Python 2.7.

python numpy

1
推荐指数
1
解决办法
215
查看次数