# How to define a Python class in a module with PyCall?

**URL:** <https://discourse.julialang.org/t/how-to-define-a-python-class-in-a-module-with-pycall/72634>\
**Category:** General Usage\
**Tags:** pycall, module\
**Created:** [December 6, 2021, 7:00am UTC](https://discourse.julialang.org/t/how-to-define-a-python-class-in-a-module-with-pycall/72634 "2021-12-06T07:00:24Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![nxtruong](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/nxtruong/32/7991_2.png) [@nxtruong](https://discourse.julialang.org/u/nxtruong)\
**Post date:** [December 6, 2021, 7:00am UTC](https://discourse.julialang.org/t/how-to-define-a-python-class-in-a-module-with-pycall/72634/1 "2021-12-06T07:00:24Z")

</div>

I want to write a Julia module in which I define a Python class using PyCall. Using an example in the README of PyCall, a MWE:

```julia
module parent
using PyCall

const pypoly = PyNULL()
function __init__ ()
    copy!(pypoly, pyimport("numpy.polynomial"))
end

@pydef mutable struct Doubler <: pypoly.Polynomial
    function __init__ (self, x=10)
        self.x = x
    end
    my_method(self, arg1::Number) = arg1 + 20
    x2.get(self) = self.x * 2
    function x2.set!(self, new_val)
        self.x = new_val / 2
    end
end

end

```

Using this module failed with the error message:

```julia
ERROR: LoadError: ArgumentError: ref of NULL PyObject
Stacktrace:
 [1] _getproperty
   @ ~/.julia/packages/PyCall/3fwVL/src/PyCall.jl:299 [inlined]
 [2] __getproperty(o::PyCall.PyObject, s::Symbol)
   @ PyCall ~/.julia/packages/PyCall/3fwVL/src/PyCall.jl:306
 [3] getproperty(o::PyCall.PyObject, s::Symbol)
   @ PyCall ~/.julia/packages/PyCall/3fwVL/src/PyCall.jl:312
 [4] top-level scope
   @ ~/.julia/packages/PyCall/3fwVL/src/pyclass.jl:205
 [5] include(fname::String)
   @ Base.MainInclude ./client.jl:451
 [6] top-level scope
   @ REPL[1]:1
in expression starting at ~/Downloads/testmodule.jl:1

```

I guess the problem was with the part `<: pypoly.Polynomial` in `@pydef` during pre-compilation because at that time, `pypoly` is still null. Is there any way to achieve this? I tried disabling precompilation but still got the error.

---

<div class="post-metadata">

**Author:** ![cjdoris](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/cjdoris/32/213133_2.png) [@cjdoris](https://discourse.julialang.org/u/cjdoris)\
**Post date:** [December 6, 2021, 7:22am UTC](https://discourse.julialang.org/t/how-to-define-a-python-class-in-a-module-with-pycall/72634/2 "2021-12-06T07:22:50Z")

</div>

You can define the class in ` __init__ ` too and `copy!` it, just like you do for `pypoly`.
