python - Is it OK to name an instance the same as a module? -
i find 'natural' name both module containing class definition , instances of class in lowercase, , use camel-case class name. example, want this:
in [2]: publisher import publisher in [3]: publisher = publisher() here have module named publisher, instance of publisher called same way. seems module , instance both 'work' expected:
in [4]: publisher import randomdata in [5]: publisher.random.uuid() out[5]: 'c490508d-2071-536e-2f38-4b03b04351e1' where i've imported class module , called instance method. python 'understand context' whether mean module or instance? ok re-use names in way?
you not shadowing anything, no name being reused here. name publisher not being used in namespace until created instance publisher = publisher(). if tried use name publisher right after from publisher import publisher line, you'd nameerror exception.
that's because from <module> import <name> form sets <name> in namespace. doesn't matter <name> imported from; @ no point <module> name in namespace.
put differently, from publisher import publisher statement translates to:
if 'publisher' not in sys.modules: # find , load publisher module # sys.modules['publisher'] = newly_loaded_module publisher = sys.modules['publisher'].publisher # set publisher global except name sys never set in namespace, python accesses sys.modules directly internally.
so, technical point of view: no, fine.
you may find using module name instance variable can create confusion name refers to future reader of code, if not python.
you may have gotten confused with
import publisher publisher = publisher.publisher() that would shadow module. line import publisher sets global name publisher, , on next line replace publisher new object reference.
cast same sys.modules language, you'd doing this:
if 'publisher' not in sys.modules: # find , load publisher module # sys.modules['publisher'] = newly_loaded_module publisher = sys.modules['publisher'] # set publisher global publisher = publisher.publisher() # set publisher global else that's fine too, unless expect publisher.publisher() work again later on. publisher no longer references module, cause issues. yet more confusing human readers.
Comments
Post a Comment