简体   繁体   中英

How to access variables in the caller library?

Let's say Library A depends on Library B, but in Library B, some piece of codes needs to access an object in Library A. Specifically, I want to check:

if isinstance(section, Section)

Because "Section" is a class defined in Library A, how can I make 'Section' available in Library, so that I can import:

from xxx import Section

Is this possible at all? And what's the normal solution?

A library is supposed to be a self-contained (other than the libraries it depends on) set of code. If you have two sets of code that both depend on each other, then they aren't really separate libraries; you should put them in the same library. If you want to keep some separation between them, you can encapsulate both as separate objects that reference each other.

The usual solution is to pass all the information in Library A to the function or class or such in Library B that needs that information as parameters . These can be parameters in a function call or attributes in an object that is a parameter in a function call or attributes in an object that Library B passes to Library A or something like that.

That means programming the functions and classes in Library B so that they ask for all needed information. If you don't know what information they need while coding Library B, you are doing it wrong.

Doing anything else is bad programming practice. You want to make it perfectly clear what information each function and module needs to do its work. Do that by passing parameters.

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