import - Python class, data structure and proper architecture -


i'm writing program, request user information different services, puts them in ways. manages stuff , slack interaction. python projects problematic @ size. imports start become recursive , handling data around becomes annoying.

a quick example of problem come across can shown simple example. have main module (here a) creates main objects (singletons). these objects need call functions each other, use main connector. in given example don't understand when b created list requests (none) nonetype. getter function not way go, helped in situation. have tips, reads point, how structure middle-sized python programs. thanks!

import b  some_list = none b = none  def get_list():     return some_list  if __name__ == "__main__":     some_list = [1,2,3]     b = b.b()     print b.my_list 

and module b

from import get_list  class b:     def __init__(self):         self.my_list = get_list().map(lambda v : v * 2) # crash here! 

you have two copies of main module now, each separate entry in sys.modules:

  1. the initial python script, started command-line, called __main__.

  2. you imported a.py file a module. separate __main__ module.

yes, same source file provided both modules, python sees them distinct.

as result, second copy not have if __name__ == '__main__': block executed, because __name__ variable set 'a' instead. such, a.some_list , a.b remain set none; wanted __main__.some_list , __main__.b instead.

don't put code in main entry point other modules need import have access to. pass in such dependencies, or have them managed separate module both main module , other modules can import.

you could, example, pass in function b() class:

b = b.b(get_list) 

Comments

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -