[Chicago] Avoiding circular imports
Ken Schutte
kenschutte at gmail.com
Sun Jan 8 20:30:12 EST 2017
Try this experiment:
=== api.py ===
print("api: top")
import models
print("api: models.Company exits? " + repr(hasattr(models,"Company")))
=== models.py ===
print("models: top")
import api
class Company:
pass
print("models: Company has been defined")
run it:
$ python api.py
api: top
models: top
api: top
api: models.Company exits? False
models: Company has been defined
api: models.Company exits? True
It can be a bit confusing, but hopefully it shows what is happening
and how imports work. Your best bet is probably to rearrange things.
For example, use models.Company within a function (wouldn't be called
directly when being imported), then call that from somewhere else.
Ken
On Sun, Jan 8, 2017 at 4:26 PM, Adam Yala <adamkyala at gmail.com> wrote:
> I tried their method, when I did I got an AttributeError: module 'models'
> has no attribute 'Company' even through it most definitely does contain that
> class.
>
> On Sun, Jan 8, 2017 at 4:12 PM, Joshua Herman <zitterbewegung at gmail.com>
> wrote:
>>
>> Searching on how to fix this on stack overflow it appears you can do this
>> with absolute imports.
>>
>> http://stackoverflow.com/questions/7336802/how-to-avoid-circular-imports-in-python
>> > On Jan 8, 2017, at 4:05 PM, Adam Yala <adamkyala at gmail.com> wrote:
>> >
>> > I'm trying to write a python wrapper for a web api. I have two files,
>> > api.py and models.py. api.py contains a Client class used to make requests
>> > to the web api. models.py contains objects from the web api in python form.
>> >
>> > api.py has the line: from models import Company
>> > models.py has the line: from api import Client
>> >
>> > The Company class uses the Client class to make other needed web api
>> > calls (like getting Employees). The Client class returns instances of
>> > Company after web api calls.
>> >
>> > However, I'm getting circular import errors. Is there a safer way to
>> > implement these imports? I've tried absolute imports and relative imports,
>> > but both throw errors.
>> >
>> > If anyone has any guides or good reads on writing web api wrappers, I'd
>> > love to give them a read. My google-fu has failed me on finding good
>> > resources.
>> > _______________________________________________
>> > Chicago mailing list
>> > Chicago at python.org
>> > https://mail.python.org/mailman/listinfo/chicago
>>
>> _______________________________________________
>> Chicago mailing list
>> Chicago at python.org
>> https://mail.python.org/mailman/listinfo/chicago
>
>
>
> _______________________________________________
> Chicago mailing list
> Chicago at python.org
> https://mail.python.org/mailman/listinfo/chicago
>
More information about the Chicago
mailing list