简体   繁体   中英

Is there an easy way to treat multiple files as a single script?

I am working on a program in Python (with Pycharm), where about half of the code is taken up by classes and functions. The program is now quite long and it is written in a single file. A lot of time would be saved if I could divide the classes, functions, and the rest of the code into 3 separate files. At the moment I can't do that due to circular imports, which causes the statement “from FunctionDocument import * ” to not work when written in the main document.

I am aware that circular imports is unprofessional and unrecommended. But it makes no sense to me why it would NOT be possible to simply add one or two lines that instructs Python to treat 3 separate files as if they were all written in a single one - EVEN if they depend on each other.

I know that this can be solved by rewriting the code to make it non-circular, and that creating a Viritual Environment might also solve the problem. But is there really no other way?

If you have circular references, you probably have an underlying problem with the design of your solution. My recommendation would be to modularize your design.

You should not be thinking on partitioning your code in an arbitrary number of files (for example, 3), but to create module folders, separated __init__.py files to initialize each module and separated files for each class. At first, it may seem like a hassle to have many small files, but you will soon see how more maintainable that approach is.

Regrading circular dependencies, you may have issues with the dependencies between classes. Classes should not depend on each other. Dependencies should be unidirectional. For example, Dog may depend on Animal by extending it. But Animal cannot reference the Dog class. This doesn't mean that it cannot collaborate with it. For example, by using methods that are defined at the Dog class.

One of the main tools for reducing dependencies between classes is duck typing . You don't need to import a class to use its methods. If the object is passed as an argument to the method, you can send messages to that object without knowing its class.

This is a good article about structuring a Python project. If you follow this approach, you will quickly find an improvement on code clarity and an enhanced productivity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM