接收全局变量(Cython) [英] Recieve global variable (Cython)

查看:177
本文介绍了接收全局变量(Cython)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在jupyter笔记本中使用Cython。

I am using Cython in jupyter notebook.

据我所知,Cython会编译def函数。

As I know, Cython compiles def functions.

但是当我想用全局变量调用函数时没有看到。

But when I want to call function with global variable it doesn't see it.

是否有任何方法可以调用带有变量的函数?

Are there any method to call function with variable?

one1 = 1
%%cython
cimport numpy as np
cdef nump(number1):
    return number1 + 1
nump(one1)

****这是示例代码,显示主持人

****This is sample code, to show moderators

推荐答案

Ipython 会话中,我可以执行以下操作:

In an Ipython session I can do:

In [2]: %load_ext Cython
In [3]: one = 1
In [4]: %%cython
   ...: def foo(num):
   ...:    return num + 1
   ...: 
In [5]: foo(one)
Out[5]: 2

即我定义了一个 cython 函数,但是使用全局变量。

That is I define a cython function, but call it from Python with the global variable.

如果用 cdef 定义函数,则需要用 def 函数。 fooc 在Python中不可见。

If I define the function with cdef I need to invoke it with a def function. fooc is not visible from Python.

In [9]: %%cython
   ...: cdef fooc(num):
   ...:    return num + 2
   ...: def foo_call(num):
   ...:    return fooc(num)
   ...: 
In [10]: foo_call(one)
Out[10]: 3

如果我尝试在 cython one >文件(魔术单元),我得到一个错误,等效于Python NameError

If I attempt to use one from within the cython file (magic cell) I get an error, the equivalent of a Python NameError

In [8]: %%cython
   ...: cdef fooc(num):
   ...:    return num + 2
   ...: print(fooc(one))
   ...: 

Error compiling Cython file:
...
/home/paul/.cache/ipython/cython/....: undeclared name not builtin: one

ipython 会话变量一个

The ipython session variable one is not visible from within the magic cell.

根据@DavidW的答案,此导入的工作原理:

Working from @DavidW's answer, this import works:

In [14]: %%cython
    ...: from __main__ import one
    ...: cdef fooc(num):
    ...:    return num + 2
    ...: print(fooc(one))
    ...: 
3

fooc 无法从Python访问。

This fooc is not accessible from Python.

请注意,导入使用编译时 one 的值。

Note that the import uses the value of one at compile time.

In [22]: %%cython
    ...: from __main__ import one
    ...: cdef fooc(num):
    ...:    return num + 20
    ...: def fooc_call():
    ...:    print(fooc(one))
    ...: 
    ...: 
In [23]: fooc_call()
21
In [24]: one=343           # new value
In [25]: fooc_call()        # no change
21
In [26]: foo_call(one)     # uses the current value
Out[26]: 345

这篇关于接收全局变量(Cython)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆