Cython: как я могу импортировать несколько классов или объектов из одного файла .pyxC++

Программы на C++. Форум разработчиков
Ответить Пред. темаСлед. тема
Anonymous
 Cython: как я могу импортировать несколько классов или объектов из одного файла .pyx

Сообщение Anonymous »

Для простоты я дам вам, ребята, мой .pyx.
У меня есть файл Geometry.pyx, и в этом файле есть классы Segment, Angle и Circle.
cimport Geometry

# Define Python classes
cdef class Segment:
def __cinit__(self, float length):
self.c_segment = make_shared[_Segment](length)

def get_length(self) -> float:
return self.c_segment.get().get_length()

cdef class Angle:

def __cinit__(self, float degrees):
self.c_angle = make_shared[_Angle](degrees)

def get_degrees(self) -> float:
return self.c_angle.get().get_degrees()

def get_radians(self) -> float:
return self.c_angle.get().get_radians()

cdef class Circle:

def __cinit__(self, float radius):
self.c_circle = make_shared[_Circle](radius)

def get_radius(self) -> float:
return self.c_circle.get().get_radius()

def get_diameter(self) -> float:
return self.c_circle.get().get_diameter()

def get_area(self) -> float:
return self.c_circle.get().get_area()

def get_perimeter(self) -> float:
return self.c_circle.get().get_perimeter()

Как мне написать файл setup.py?
Я написал, как показано ниже, но получил ошибку
from setuptools import setup, Extension, find_packages
from Cython.Build import cythonize

# extension = Extension(
# "Geometry.Geometry",
# ["src/Geometry/Geometry.pyx", "../cpp/lib/src/Geometry.cpp"],
# include_dirs=["../cpp/lib/include"],
# extra_compile_args=['-std=c++17', '-O3'],
# language='c++'
# )

extension_segment = Extension(
"Geometry.Segment",
["src/Geometry/Geometry.pyx", "../cpp/lib/src/Geometry.cpp"],
include_dirs=["../cpp/lib/include"],
extra_compile_args=['-std=c++17', '-O3'],
language='c++'
)

extension_angle= Extension(
"Geometry.Angle",
["src/Geometry/Geometry.pyx", "../cpp/lib/src/Geometry.cpp"],
include_dirs=["../cpp/lib/include"],
extra_compile_args=['-std=c++17', '-O3'],
language='c++'
)

extension_circle= Extension(
"Geometry.Circle",
["src/Geometry/Geometry.pyx", "../cpp/lib/src/Geometry.cpp"],
include_dirs=["../cpp/lib/include"],
extra_compile_args=['-std=c++17', '-O3'],
language='c++'
)

setup(
name='Geometry',
version='0.1',
packages=find_packages(where='src'),
package_dir={"": "src"},
package_data={"Geometry": ["*.pyx"]},
ext_modules=cythonize(extension_segment,
compiler_directives={'language_level': 3},
include_path=["src/Geometry"],
annotate=True
)+
cythonize(extension_angle,
compiler_directives={'language_level': 3},
include_path=["src/Geometry"],
annotate=True
)+
cythonize(extension_circle,
compiler_directives={'language_level': 3},
include_path=["src/Geometry"],
annotate=True
)
)

Test.py
from Geometry import Segment, Angle, Circle

class TestGeometry:
def test_segment_length(self):
seg = Segment(10.0)
# assert seg.get_length() == 5.0
print("HELO")
#
# def test_angle_degrees(self):
# ang = Angle(90.0)
# assert ang.get_degrees() == 90.0
#
# def test_angle_radians(self):
# ang = Angle(90.0)
# assert ang.get_radians() == 1.5707963267948966 # approximately pi/2
#
# def test_circle_radius(self):
# circ = Circle(3.0)
# assert circ.get_radius() == 3.0
#
# def test_circle_diameter(self):
# circ = Circle(3.0)
# assert circ.get_diameter() == 6.0
#
# def test_circle_area(self):
# circ = Circle(3.0)
# assert circ.get_area() == 28.274333882308138 # approximately pi * r^2
#
# def test_circle_perimeter(self):
# circ = Circle(3.0)
# assert circ.get_perimeter() == 18.84955592153876 # approximately 2 * pi * r

Сообщение об ошибке
/home/punreach/Desktop/A_Folder/project-core/venv/bin/python /opt/pycharm-2024.1/plugins/python/helpers/pycharm/_jb_pytest_runner.py --target test_geometry.py::TestGeometry.test_segment_length
Testing started at 오후 6:11 ...
Launching pytest with arguments test_geometry.py::TestGeometry::test_segment_length --no-header --no-summary -q in /home/punreach/Desktop/A_Folder/project-core/lib/Geometry/cython/test

============================= test session starts ==============================
collecting ...
test/test_geometry.py:None (test/test_geometry.py)
test_geometry.py:1: in
from Geometry import Segment, Angle, Circle
../../../../venv/lib/python3.10/site-packages/Geometry-0.1-py3.10-linux-x86_64.egg/Geometry/__init__.py:1: in
from .Geometry import *
src/Geometry/Geometry.pyx:1: in init Geometry.Geometry
???
E AttributeError: partially initialized module 'Geometry' has no attribute 'Segment' (most likely due to a circular import)
collected 0 items / 1 error

=============================== 1 error in 0.02s ===============================
ERROR: found no collectors for /home/punreach/Desktop/A_Folder/project-core/lib/Geometry/cython/test/test_geometry.py::TestGeometry::test_segment_length

Process finished with exit code 4


Подробнее здесь: https://stackoverflow.com/questions/783 ... e-pyx-file
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение
  • Cython.Compiler.Errors.CompileError в файле pyx
    Anonymous » » в форуме Python
    0 Ответы
    34 Просмотры
    Последнее сообщение Anonymous
  • «pip install pytetgen» не может найти модуль Cython, но «pip install Cython» показывает, что он уже установлен
    Anonymous » » в форуме Python
    0 Ответы
    88 Просмотры
    Последнее сообщение Anonymous
  • Каков тип аргумента ниже в Pyx?
    Гость » » в форуме Python
    0 Ответы
    26 Просмотры
    Последнее сообщение Гость
  • «ValueError: 'editdistance/bycython.pyx' не соответствует ни одному файлу» при установке editdistance для AlphaGeometry
    Anonymous » » в форуме Python
    0 Ответы
    23 Просмотры
    Последнее сообщение Anonymous
  • PyX установлен неправильно при использовании scapy
    Anonymous » » в форуме Python
    0 Ответы
    18 Просмотры
    Последнее сообщение Anonymous

Вернуться в «C++»