简体   繁体   中英

Python convention for mandating variable prefix for automation purposes

I am creating Mongo document schemas using Mongo engine, and I would like to use variable names as indicators of where the data will come from. For example:

class MyDocument(Document):
     source1_name = something
     source1_age = something

     source2_x = something

Idea is that while variable names can be anything, those pre-fixes will be important in execution of the code, because automation will populate those variables from different data sources before putting them in Mongo.

I will definitely have a comment that explains naming convention, but I am wondering if there is a PEP8 naming convention for cases like this, to give a visual queue to a developer that prefix means something.

If the answer is no - are there some other "best practices" for when variable name itself is used in the rest of the code?

For context, in a past life I worked on a code base that had been developed on for over 25 years (and counting). The code base was littered with these prefixes that made sense at the time but for many reasons over time where the data came from no longer made sense.

  • Source 2 became a better place to retrieve foo than source 1
  • Source 1 went out of business
  • Source 1 was replaced
  • etc.

The problem came that the usage of the fields was so far ingrained that it would have been a massive task to update so their prefixs meaning became irrelevant.

The important part of variables at all times is what they represent, not where they come from so I wouldnt really advise any prefix for this use case. What I would advise is just keep the variables simple and initialise them under methods that explain where they come from if need be.

def __init__(self):
    self.init_source1()
    self.init_source2()

def init_source1(self):
    self.name = foo

def init_source2(self):
    self.x = bar

Looking into the code base then its clear where the source is, and it can be changed as needed

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