Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I specify a pointer as a parameter to a function in Python?

I'm trying to define a function (initdeque()) that takes a pointer to an instance of the deque class. So this is what I tried:

from ctypes import *

class deque(Structure):
        pass

deque._fields_ = [("left",POINTER(node)),("right",POINTER(node))]

def initdeque(class deque *p):
        p.left=p.right=None

But this code gives a syntax error:

  def initdeque(class deque *p):
                      ^
  SyntaxError: invalid syntax

What is the correct syntax?

like image 296
kiran Avatar asked Dec 03 '25 16:12

kiran


1 Answers

There is no way to specify the type of Python variables, so the declaration of initdequeue should just say:

def initdeque(p):
  p.left = p.right = None

Instead of having a random function doing the initialization, you should consider using an initializer:

class deque(Structure):
  _fields_ = [("left",POINTER(node)), ("right",POINTER(node))]

  def __init__(self):
    self.left = self.right = None

Now, to create a new instance, just write

 p = dequeue()
like image 84
phihag Avatar answered Dec 05 '25 04:12

phihag



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!