osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Enums are Singletons - but not always?


On Sun, May 24, 2020 at 5:58 AM Kushal Kumaran <kushal at locationd.net> wrote:
>
> "Ralf M." <Ralf_M at t-online.de> writes:
>
> > Below are a simplified code sample, the results when I run it and my
> > thoughts.
> >
> > ##### Code of mod1.py #####
> > import enum, mod2
> > def main():
> >     a = mod2.getA()
> > ##### End of mod1.py #####
> >
> > ##### Code of mod2.py #####
> > import mod1
> > def getA():
> >     return mod1.En.A
> > ##### End of mod2.py #####
> >
> I think of circular dependencies as a code smell.  You can move the enum
> definition into a separate module, and have both mod1 and mod2 import
> that, or like you say, by moving the main function into its own module.
> Maybe you can explain why you don't want this.

Correct - and especially since you're using the main module also as a
module. Currently, that is something you just plain shouldn't do. You
end up with one copy of the module called __main__ and another one
called mod1, and they're completely independent. Just don't do that.

However, there HAVE been some proposals to make this sort of thing
work. In general, they'd end up doing something like having the module
inserted into sys.modules twice, once as __main__ and once as mod1, so
you end up getting the same module in both cases. That would work,
since (with only one module) there'd only be one En class. I don't
think any such proposal has gotten fully serious yet, but if this is
something you're interested in (or feel strongly about), dig through
the python-ideas archives to see some of the arguments for and
against.

ChrisA