Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python create/import custom module in same directory

Tags:

python

I'm trying to create a simple python script and import a couple of custom classes. I'd like to do this as one module. Here is what I have:

point/point.py

class Point:
   """etc."""

point/pointlist.py

class PointList:
   """etc."""

point/__init__.py

from . import point, pointlist

script.py

import sys, point
verbose = False
pointlist = PointList()

When I run script.py I get NameError: name 'PointList' is not defined

What's weird is that in point/, all three of the module files (__init__, pointlist, point) have a .pyc version created that was not there before, so it seems like it is finding the files. The class files themselves also compile without any errors.

I feel like I'm probably missing something very simple, so please bear with me.

like image 285
Explosion Pills Avatar asked Feb 02 '23 14:02

Explosion Pills


1 Answers

Sorry, I seem to have made a blunder in my earlier answer and comments:

The problem here is that you should access the objects in point through the module you import:

point/__init__.py:

from point import Point
from pointlist import PointList

script.py:

import sys, point
verbose = False
pointlist = point.PointList()

You access PointList through the import point which imports whatever is in __init__.py

If you want to access PointList and Point directly you could use from point import Point, PointList in script.py or the least preferable from point import *

Again, sorry for my earlier error.

like image 175
immortal Avatar answered Feb 05 '23 06:02

immortal