Should all namedtuples be in a separate file?

I use quite a lot namedtuple

in my Python codebase and they get littered in all files .py

. Is it good practice to extract all of these declarations into a separate file, or should they stay where they are used?

In some cases, other modules need to use the reference namedtuples

in separate modules, as this is the definition of interfaces - they expect namedtuples

. What is the recommended Pythonic technique for organizing various namedtuples

, especially cross-module links?

+3


source to share


1 answer


The thought process used to determine where the named elements should be placed is no different than what you would use for any other line of code:

  • Modules define logical units of functionality. Some pieces of code may never need to know or interact with another piece of code. The identification of these boundary lines is a strong hint as to where to break the code into modules.

  • Modules encapsulate an interface. They give you the ability to define the API through which all other pieces of code interact, as well as isolate the implementation details in a module. Isolating code in modules makes it easier to know where to focus your attention when you want to change the implementation while maintaining the API.

Once you've defined the logical blocks (like modules) and the API through which the logical blocks will interact, it should be clearer where to place the named items.



If one module X

needs to import another module Y

for any other reason than to define named elements, then it might make sense to place the named elements in a separate module Z

because you found the boundary line.

If, however, there was a X

need to import Y

anyway, it really wouldn't matter much if the named elements were placed in a separate module, since everywhere you import Y

are, too import Z

.

Now it is often the case that it X

does not need all the functionality provided Y

, and so you might be tempted to strip out that smaller bit that X

needs a separate module. But after a certain point splitting every little bit into it, owning a module - crazy - becomes more burdensome to have many small modules, rather than one medium-sized module. Where that line is exactly what's in between is a matter of taste and what you think of as logical units of functionality.

+4


source







All Articles