equivalent to C pointer

Neil Cerutti neilc at norwich.edu
Thu Apr 18 14:07:32 EDT 2013


On 2013-04-18, abdelkader belahcene <abelahcene at gmail.com> wrote:
> Thanks for answer,
> but with C  we can compile the trapeze function and put it in
> librairy, If we try to save the trapeze alone in  package to
> import it later,  I think, I am not sure it will be refused
> because F1 and sin are not define !!!     this is the power of
> the C pointers !!! the link is dynamic

There's no linking stage in Python. Everything you use must be
defined before you use it.

In Python you can put trapeze in a library, and it will be able
to accept any old function under the sun when you call it, as
long as that function is defined.

in trapeze.py:

  def trapeze(func, left, right, step):
      return sum((func(x) + func(x + step)) * step * 0.5
                 for x in range(left, right, step))
               
in file1.py:

  import trapeze
  
  def square(x):
      return x*x
  
  print(trapeze.trapeze(square, 0, 3, 2.5))


if file2.py:

  import trapeze
  import math
  
  print(trapeze.trapeze(math.sin, 1.3, 2.5, 1.0))

The functions square and sin are both defined before you pass
them to trapeze, so all is well. Trapeze doesn't know or care about
the signature of those functions until it actually tries to call
them. At that time, if either one isn't defined properly Python
will raise an exception.

-- 
Neil Cerutti



More information about the Python-list mailing list