1

I have seen a number of questions on here and other places asking the same thing, but the answers they are giving are either not working or I am misunderstanding the answer.

I am using Python 3. I need to import CityNames.py into Cities.py.

I have the following directories:

CityBorders
  | Cities.py
  | CityNames.py

and the following code in the files:

Cities.py

from CityNames import *
from random import choice


class City:
    def __init__(self):
        self.set_name()

    def set_name(self):
        if hasattr(self, 'name'):
            city_names[self.name] = None

        self.name = choice([n for n, c in city_names.items() if c is None])
        city_names[self.name] = self


def get_cities(count):
    return [City() for _ in range(min(count, len(city_names)))]


cities = get_cities(20)
print([c.name for c in cities])

CityNames.py

city_names = {
    "Macclesfield": None,
    "Blue Field": None,
    "Farnworth": None,
    "Foolshope": None,
    "Waterrun": None,
    "Murtovaara": None,
    "Nancledra": None,
    "Aeberuthey": None,
    .
    .
    .
    "Middlesbrough": None,
    "Balerno": None
}

With this code, the program seems to run correctly, but PyCharm is showing a fatal error saying, "This inspection detects names that should resolve but don't. Due to dynamic dispatch and duck typing, this is possible in a limited but useful number of cases. Top-level and class-level items are supported better than instance items." It adds a red underline under the word CityNames and city_names.

When I add a . before CityNames (from .CityNames import *), the errors go away, but the code stops working giving me the following Error codes when I try to run it:

Traceback (most recent call last):
  File "S:/Makai/Projects/Artifitial Art/CityBorders/Cities.py", line 1, in <module>
    from .CityNames import *
ModuleNotFoundError: No module named '__main__.CityNames'; '__main__' is not a package

Also, when looking at the questions others have asked, many of them are talking about adding __init__.py to the directory. I'm not sure why that is or why I would add it. When I do add it, it doesn't seem to make a difference. Do I need to have something in the file or just leave it blank?

martineau
  • 119,623
  • 25
  • 170
  • 301
ToMakPo
  • 855
  • 7
  • 27

1 Answers1

1

I also use PyCharm, so

How about :

from . import CityNames.city_names as cn

In my django projects I use:

from . import views

And it works perfect!

stPhoenix
  • 21
  • 1
  • 6