Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

🛁 Clean Code concepts adapted for Python

License

NotificationsYou must be signed in to change notification settings

Ivanhoeee/clean-code-python

 
 

Repository files navigation

Build Status

Table of Contents

  1. Introduction
  2. Variables
  3. Functions
  4. Objects and Data Structures
  5. Classes
    1. S: Single Responsibility Principle (SRP)
    2. O: Open/Closed Principle (OCP)
    3. L: Liskov Substitution Principle (LSP)
    4. I: Interface Segregation Principle (ISP)
    5. D: Dependency Inversion Principle (DIP)
  6. Don't repeat yourself (DRY)

Introduction

Software engineering principles, from Robert C. Martin's bookClean Code,adapted for Python. This is not a style guide. It's a guide to producingreadable, reusable, and refactorable software in Python.

Not every principle herein has to be strictly followed, and even fewer will be universallyagreed upon. These are guidelines and nothing more, but they are ones codified over manyyears of collective experience by the authors ofClean Code.

Inspired fromclean-code-javascript

Targets Python3.7+

Variables

Use meaningful and pronounceable variable names

Bad:

importdatetimeymdstr=datetime.date.today().strftime("%y-%m-%d")

Good:

importdatetimecurrent_date:str=datetime.date.today().strftime("%y-%m-%d")

⬆ back to top

Use the same vocabulary for the same type of variable

Bad:Here we use three different names for the same underlying entity:

defget_user_info():passdefget_client_data():passdefget_customer_record():pass

Good:If the entity is the same, you should be consistent in referring to it in your functions:

defget_user_info():passdefget_user_data():passdefget_user_record():pass

Even betterPython is (also) an object oriented programming language. If it makes sense, package the functions together with the concrete implementationof the entity in your code, as instance attributes, property methods, or methods:

fromtypingimportUnion,Dict,TextclassRecord:passclassUser:info :str@propertydefdata(self)->Dict[Text,Text]:return {}defget_record(self)->Union[Record,None]:returnRecord()

⬆ back to top

Use searchable names

We will read more code than we will ever write. It's important that the code we do write isreadable and searchable. Bynot naming variables that end up being meaningful forunderstanding our program, we hurt our readers.Make your names searchable.

Bad:

importtime# What is the number 86400 for again?time.sleep(86400)

Good:

importtime# Declare them in the global namespace for the module.SECONDS_IN_A_DAY=60*60*24time.sleep(SECONDS_IN_A_DAY)

⬆ back to top

Use explanatory variables

Bad:

importreaddress="One Infinite Loop, Cupertino 95014"city_zip_code_regex=r"^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$"matches=re.match(city_zip_code_regex,address)ifmatches:print(f"{matches[1]}:{matches[2]}")

Not bad:

It's better, but we are still heavily dependent on regex.

importreaddress="One Infinite Loop, Cupertino 95014"city_zip_code_regex=r"^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$"matches=re.match(city_zip_code_regex,address)ifmatches:city,zip_code=matches.groups()print(f"{city}:{zip_code}")

Good:

Decrease dependence on regex by naming subpatterns.

importreaddress="One Infinite Loop, Cupertino 95014"city_zip_code_regex=r"^[^,\\]+[,\\\s]+(?P<city>.+?)\s*(?P<zip_code>\d{5})?$"matches=re.match(city_zip_code_regex,address)ifmatches:print(f"{matches['city']},{matches['zip_code']}")

⬆ back to top

Avoid Mental Mapping

Don’t force the reader of your code to translate what the variable means.Explicit is better than implicit.

Bad:

seq= ("Austin","New York","San Francisco")foriteminseq:#do_stuff()#do_some_other_stuff()# Wait, what's `item` again?print(item)

Good:

locations= ("Austin","New York","San Francisco")forlocationinlocations:#do_stuff()#do_some_other_stuff()# ...print(location)

⬆ back to top

Don't add unneeded context

If your class/object name tells you something, don't repeat that in yourvariable name.

Bad:

classCar:car_make:strcar_model:strcar_color:str

Good:

classCar:make:strmodel:strcolor:str

⬆ back to top

Use default arguments instead of short circuiting or conditionals

Tricky

Why write:

importhashlibdefcreate_micro_brewery(name):name="Hipster Brew Co."ifnameisNoneelsenameslug=hashlib.sha1(name.encode()).hexdigest()# etc.

... when you can specify a default argument instead? This also makes it clear thatyou are expecting a string as the argument.

Good:

fromtypingimportTextimporthashlibdefcreate_micro_brewery(name:Text="Hipster Brew Co."):slug=hashlib.sha1(name.encode()).hexdigest()# etc.

⬆ back to top

Functions

Function arguments (2 or fewer ideally)

Limiting the amount of function parameters is incredibly important because it makestesting your function easier. Having more than three leads to a combinatorial explosionwhere you have to test tons of different cases with each separate argument.

Zero arguments is the ideal case. One or two arguments is ok, and three should be avoided.Anything more than that should be consolidated. Usually, if you have more than twoarguments then your function is trying to do too much. In cases where it's not, mostof the time a higher-level object will suffice as an argument.

Bad:

defcreate_menu(title,body,button_text,cancellable):pass

Java-esque:

classMenu:def__init__(self,config:dict):self.title=config["title"]self.body=config["body"]# ...menu=Menu(    {"title":"My Menu","body":"Something about my menu","button_text":"OK","cancellable":False    })

Also good

fromtypingimportTextclassMenuConfig:"""A configuration for the Menu.    Attributes:        title: The title of the Menu.        body: The body of the Menu.        button_text: The text for the button label.        cancellable: Can it be cancelled?    """title:Textbody:Textbutton_text:Textcancellable:bool=Falsedefcreate_menu(config:MenuConfig)->None:title=config.titlebody=config.body# ...config=MenuConfig()config.title="My delicious menu"config.body="A description of the various items on the menu"config.button_text="Order now!"# The instance attribute overrides the default class attribute.config.cancellable=Truecreate_menu(config)

Fancy

fromtypingimportNamedTupleclassMenuConfig(NamedTuple):"""A configuration for the Menu.    Attributes:        title: The title of the Menu.        body: The body of the Menu.        button_text: The text for the button label.        cancellable: Can it be cancelled?    """title:strbody:strbutton_text:strcancellable:bool=Falsedefcreate_menu(config:MenuConfig):title,body,button_text,cancellable=config# ...create_menu(MenuConfig(title="My delicious menu",body="A description of the various items on the menu",button_text="Order now!"    ))

Even fancier

fromtypingimportTextfromdataclassesimportastuple,dataclass@dataclassclassMenuConfig:"""A configuration for the Menu.    Attributes:        title: The title of the Menu.        body: The body of the Menu.        button_text: The text for the button label.        cancellable: Can it be cancelled?    """title:Textbody:Textbutton_text:Textcancellable:bool=Falsedefcreate_menu(config:MenuConfig):title,body,button_text,cancellable=astuple(config)# ...create_menu(MenuConfig(title="My delicious menu",body="A description of the various items on the menu",button_text="Order now!"    ))

Even fancier, Python3.8+ only

fromtypingimportTypedDict,TextclassMenuConfig(TypedDict):"""A configuration for the Menu.    Attributes:        title: The title of the Menu.        body: The body of the Menu.        button_text: The text for the button label.        cancellable: Can it be cancelled?    """title:Textbody:Textbutton_text:Textcancellable:booldefcreate_menu(config:MenuConfig):title=config["title"]# ...create_menu(# You need to supply all the parametersMenuConfig(title="My delicious menu",body="A description of the various items on the menu",button_text="Order now!",cancellable=True    ))

⬆ back to top

Functions should do one thing

This is by far the most important rule in software engineering. When functions do morethan one thing, they are harder to compose, test, and reason about. When you can isolatea function to just one action, they can be refactored easily and your code will read muchcleaner. If you take nothing else away from this guide other than this, you'll be aheadof many developers.

Bad:

fromtypingimportListclassClient:active:booldefemail(client:Client)->None:passdefemail_clients(clients:List[Client])->None:"""Filter active clients and send them an email.    """forclientinclients:ifclient.active:email(client)

Good:

fromtypingimportListclassClient:active:booldefemail(client:Client)->None:passdefget_active_clients(clients:List[Client])->List[Client]:"""Filter active clients.    """return [clientforclientinclientsifclient.active]defemail_clients(clients:List[Client])->None:"""Send an email to a given list of clients.    """forclientinget_active_clients(clients):email(client)

Do you see an opportunity for using generators now?

Even better

fromtypingimportGenerator,IteratorclassClient:active:booldefemail(client:Client):passdefactive_clients(clients:Iterator[Client])->Generator[Client,None,None]:"""Only active clients"""return (clientforclientinclientsifclient.active)defemail_client(clients:Iterator[Client])->None:"""Send an email to a given list of clients.    """forclientinactive_clients(clients):email(client)

⬆ back to top

Function names should say what they do

Bad:

classEmail:defhandle(self)->None:passmessage=Email()# What is this supposed to do again?message.handle()

Good:

classEmail:defsend(self)->None:"""Send this message"""message=Email()message.send()

⬆ back to top

Functions should only be one level of abstraction

When you have more than one level of abstraction, your function is usually doing toomuch. Splitting up functions leads to reusability and easier testing.

Bad:

# type: ignoredefparse_better_js_alternative(code:str)->None:regexes= [# ...    ]statements=code.split('\n')tokens= []forregexinregexes:forstatementinstatements:passast= []fortokenintokens:passfornodeinast:pass

Good:

fromtypingimportTuple,List,Text,DictREGEXES:Tuple= (# ...)defparse_better_js_alternative(code:Text)->None:tokens:List=tokenize(code)syntax_tree:List=parse(tokens)fornodeinsyntax_tree:passdeftokenize(code:Text)->List:statements=code.split()tokens:List[Dict]= []forregexinREGEXES:forstatementinstatements:passreturntokensdefparse(tokens:List)->List:syntax_tree:List[Dict]= []fortokenintokens:passreturnsyntax_tree

⬆ back to top

Don't use flags as function parameters

Flags tell your user that this function does more than one thing. Functionsshould do one thing. Split your functions if they are following different codepaths based on a boolean.

Bad:

fromtypingimportTextfromtempfileimportgettempdirfrompathlibimportPathdefcreate_file(name:Text,temp:bool)->None:iftemp:        (Path(gettempdir())/name).touch()else:Path(name).touch()

Good:

fromtypingimportTextfromtempfileimportgettempdirfrompathlibimportPathdefcreate_file(name:Text)->None:Path(name).touch()defcreate_temp_file(name:Text)->None:    (Path(gettempdir())/name).touch()

⬆ back to top

Avoid side effects

A function produces a side effect if it does anything other than take a value inand return another value or values. For example, a side effect could be writingto a file, modifying some global variable, or accidentally wiring all your moneyto a stranger.

Now, you do need to have side effects in a program on occasion - for example, likein the previous example, you might need to write to a file. In these cases, youshould centralize and indicate where you are incorporating side effects. Don't haveseveral functions and classes that write to a particular file - rather, have one(and only one) service that does it.

The main point is to avoid common pitfalls like sharing state between objectswithout any structure, using mutable data types that can be written to by anything,or using an instance of a class, and not centralizing where your side effects occur.If you can do this, you will be happier than the vast majority of other programmers.

Bad:

# type: ignore# This is a module-level name.# It's good practice to define these as immutable values, such as a string.# However...fullname="Ryan McDermott"defsplit_into_first_and_last_name()->None:# The use of the global keyword here is changing the meaning of the# the following line. This function is now mutating the module-level# state and introducing a side-effect!globalfullnamefullname=fullname.split()split_into_first_and_last_name()# MyPy will spot the problem, complaining about 'Incompatible types in# assignment: (expression has type "List[str]", variable has type "str")'print(fullname)# ["Ryan", "McDermott"]# OK. It worked the first time, but what will happen if we call the# function again?

Good:

fromtypingimportList,AnyStrdefsplit_into_first_and_last_name(name:AnyStr)->List[AnyStr]:returnname.split()fullname="Ryan McDermott"name,surname=split_into_first_and_last_name(fullname)print(name,surname)# => Ryan McDermott

Also good

fromtypingimportTextfromdataclassesimportdataclass@dataclassclassPerson:name:Text@propertydefname_as_first_and_last(self)->list:returnself.name.split()# The reason why we create instances of classes is to manage state!person=Person("Ryan McDermott")print(person.name)# => "Ryan McDermott"print(person.name_as_first_and_last)# => ["Ryan", "McDermott"]

⬆ back to top

Objects and Data Structures

Coming soon

⬆ back to top

Classes

Single Responsibility Principle (SRP)

Open/Closed Principle (OCP)

Liskov Substitution Principle (LSP)

Interface Segregation Principle (ISP)

Dependency Inversion Principle (DIP)

Coming soon

⬆ back to top

Don't repeat yourself (DRY)

Try to observe theDRY principle.

Do your absolute best to avoid duplicate code. Duplicate code is bad becauseit means that there's more than one place to alter something if you need tochange some logic.

Imagine if you run a restaurant and you keep track of your inventory: all yourtomatoes, onions, garlic, spices, etc. If you have multiple lists thatyou keep this on, then all have to be updated when you serve a dish withtomatoes in them. If you only have one list, there's only one place to update!

Often you have duplicate code because you have two or more slightlydifferent things, that share a lot in common, but their differences force youto have two or more separate functions that do much of the same things. Removingduplicate code means creating an abstraction that can handle this set of differentthings with just one function/module/class.

Getting the abstraction right is critical. Bad abstractions can beworse than duplicate code, so be careful! Having said this, if you can makea good abstraction, do it! Don't repeat yourself, otherwise you'll find yourselfupdating multiple places any time you want to change one thing.

Bad:

fromtypingimportList,Text,Dictfromdataclassesimportdataclass@dataclassclassDeveloper:def__init__(self,experience:float,github_link:Text)->None:self._experience=experienceself._github_link=github_link@propertydefexperience(self)->float:returnself._experience@propertydefgithub_link(self)->Text:returnself._github_link@dataclassclassManager:def__init__(self,experience:float,github_link:Text)->None:self._experience=experienceself._github_link=github_link@propertydefexperience(self)->float:returnself._experience@propertydefgithub_link(self)->Text:returnself._github_linkdefget_developer_list(developers:List[Developer])->List[Dict]:developers_list= []fordeveloperindevelopers:developers_list.append({'experience' :developer.experience,'github_link' :developer.github_link            })returndevelopers_listdefget_manager_list(managers:List[Manager])->List[Dict]:managers_list= []formanagerinmanagers:managers_list.append({'experience' :manager.experience,'github_link' :manager.github_link            })returnmanagers_list## create list objects of developerscompany_developers= [Developer(experience=2.5,github_link='https://github.com/1'),Developer(experience=1.5,github_link='https://github.com/2')]company_developers_list=get_developer_list(developers=company_developers)## create list objects of managerscompany_managers= [Manager(experience=4.5,github_link='https://github.com/3'),Manager(experience=5.7,github_link='https://github.com/4')]company_managers_list=get_manager_list(managers=company_managers)

Good:

fromtypingimportList,Text,Dictfromdataclassesimportdataclass@dataclassclassEmployee:def__init__(self,experience:float,github_link:Text)->None:self._experience=experienceself._github_link=github_link@propertydefexperience(self)->float:returnself._experience@propertydefgithub_link(self)->Text:returnself._github_linkdefget_employee_list(employees:List[Employee])->List[Dict]:employees_list= []foremployeeinemployees:employees_list.append({'experience' :employee.experience,'github_link' :employee.github_link            })returnemployees_list## create list objects of developerscompany_developers= [Employee(experience=2.5,github_link='https://github.com/1'),Employee(experience=1.5,github_link='https://github.com/2')]company_developers_list=get_employee_list(employees=company_developers)## create list objects of managerscompany_managers= [Employee(experience=4.5,github_link='https://github.com/3'),Employee(experience=5.7,github_link='https://github.com/4')]company_managers_list=get_employee_list(employees=company_managers)

⬆ back to top

About

🛁 Clean Code concepts adapted for Python

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • Python97.6%
  • Makefile2.4%

[8]ページ先頭

©2009-2025 Movatter.jp