# Creating complex polygon with pyshp?

using the pyshp library (https://code.google.com/p/pyshp/) I am trying to create a "complex" polgon with one hole inside the main-poly plus one island-poly. It should look like this:

I used the following code from the documentation, only changing the number of points and using anticlockwise rotation for the hole:

``````import shapefile
w = shapefile.Writer(shapefile.POLYGON)
w.poly(parts=[[[0,50],[50,50],[50,0],[0,0],[0,50],[10,40],[10,10],[30,10],[30,40],[10,40],[70,20],[100,20],[100,0],[70,0],[70,20]]])
w.field('FIRST_FLD','C','40')
w.field('SECOND_FLD','C','40')
w.record('Poly','PolyTest')
w.save('TESTPOLY')
``````

I get this:

Each piece of your complex polygon, including the hole, is called a "part" in the shapefile spec. Parts are how they tie multiple distinct geometries to a single dbf record.

In pyshp, parts are a list of lists passed to the poly method. The example you followed only has one list of points within the parts. But your shapefile has 3 distinct polygons. So each one of your 3 shapes needs to be in a sub-list like this:

``````w.poly(parts=[[[0,50],[50,50],[50,0],[0,0],[0,50]],[[10,40],[10,10],[30,10],[30,40],[10,40]],[[70,20],[100,20],[100,0],[70,0],[70,20]]])
``````

``````# [[[Clockwise Part (Single)]], [[Counter Clockwise Parts (Multiple)]]]
parts_with_holes = [[[0, 50], [50, 50], [50, 0], [0, 0], [0, 50]], [[10, 40], [10, 10], [30, 10], [30, 40], [10, 40]]]
# [[Clockwise Part (Single)]]
parts_no_holes = [[10, 10], [10, 40], [30, 40], [30, 10], [10, 10]]

sf_out.field('FIRST_FLD', 'C', '40')
sf_out.field('SECOND_FLD', 'C', '40')

sf_out.poly(parts_with_holes)
sf_out.record('Poly', 'PolyTest')

sf_out.poly([parts_no_holes])
sf_out.record('Poly', 'PolyTest')
sf_out.close()
``````