SlideShare a Scribd company logo
Beyond 

the Style Guides
Mosky
It's all about time.
I can write a 4x faster program than you!
But the hardware is super powerful now,

it may be just 0.0001 ms vs. 0.0004 ms.
I can write 4x faster.
And human brain haven't changed a lot,

so it may be even 1 week vs. 1 month.
Human Time ⋙ Computer Time
- Benjamin Franklin
“Time is money.”
How to write faster?
Good language, e.g., Python
Powerful libraries
Experience
∈ The things you can't change immediately.
Understandable codebase.

i.e., codebase which has high maintainability.
∈ You can just learn from this share.
Style Guide?
# It looks okay!

count += 1
Not enough
# But it was initialized as

count = '1'
# In JavaScript, 

# there's even no an error.
You remain only 10k days in your life.
Spend time on writing exciting feature,

not debugging.
Mosky
Python Charmer at Pinkoi
The author of the Python packages
MoSQL, Clime, …
The speaker of the conferences,
PyCon TW/JP/SG, …
Also teaching Python
mosky.tw
Beyond the Style Guides
Beyond the Style Guides
Pinkoi

Pinkoi

a.k.a.
Beyond the Style Guides
Beyond the Style Guides
Thanks!
Human Brain
A Computer
Read the code line by line.
Cover all of the code, usually.
Just complain when it doesn't understand.
A Human Brain
We can't read code like a computer.
CPU is super slow, and even can't focus.
RAM is tiny, programmer especially.
Disk is losing bytes all the time.
Nobody to complain.
So we prefer to leave code alone.
But, computer is always complaining.
We jump to the failed line.
Read back from the line.
Finally, 

we leave immediately after we x it.
Or, new requirement comes.
We still jump to the related line.
Read back from the line.
Finally, 

we also leave immediately after we nish it.
We read lines randomly.
Maintainability
To understand a random line, 

how many lines do you need to read back?
Lesser → Higher maintainability
Name
Nothing But
Have a good dictionary.
Be exact to avoid ambiguity.
Be consistent to avoid misleading.
Hint, hint, and hint.
Be Exact
“Apple”
Which “Apple”?
“Apple, the company.”
apple_the_company
date_a-date_b
Which dates?
today-joined_date
user
User’s what?
user_name
user_email
name
Who’s name?
user_name
store_name
Be Consistent
Saw this in somewhere:
apple = Company('apple')
Now you read:
apple
Then you will guess it is a company. So don't:
apple = Fruit('apple')
Too Long?
The context helps.
fruit.py
apple
Type Hint
We operate variables.
count += 1
parse(input_json)
If we know how to operate it at first glance,

it saves time from tracing or running.
Not the “Type Hint” in PEP 0484
Make It Intuitive
count
should be numeric
name
string thing
names
many strings; may be a list
page
page_no
so should be numeric
event
event_key
so should be string stuff
List or Set?
requested_fields & allowed_fields
?
set(requested_fileds) & allowed_field_set
List or Generator?
large_rows
large_rows[0] # ?
large_row_gen # generator
large_row_it # iterator
Object or Dict?
user
What is the type of user?
user['name'] # ?
user.name # ?
user_dict['name']
user_d['name']
Is it a bool?
new_user
A bool? A User instance?
is_new_user
A bool? A Function?
new
user_is_new
Is it a function?
Use imperative, i.e., start with a verb.
.text
.json
A function? A string thing?
.get_text
.parse_from_json
.text # string thing
def parse(x, return_dict=False): …
?
def parse(x, to_return_dict=False): …
Explicit Unknown
arg
May be tuple, dict, or anything.
arg_x
Avoid None
d = None if failed else {}

d['key'] = value

value = d.get('key')
It causes TypeError or AttributeError in Python,
and extra effort in other language.
Be consistent in type.
Some tips
Raise exception.
Use zero and innite.
Use constant.
Filter the Nones out before return.
Content Type
User Input
The “Keys”
URL
JSON
HTML
SQL
∈ string thing
json['keyword'] # ?
Actually the json is a dict-like.
JSON: JavaScript Object Notation → a string
arg_dict = json.loads(arg_json)
Transformation
You can see the domain and codomain.
template.format(name)
If
template # -> "<a>{}</a>"
name # -> "<script src=…></script>"
!
template_html.format(escape(name))
Safe :)
“Making Wrong Code Look Wrong “
Abstract Type
it — iterator
seq — sequence
map — mapping
Structure Hint
We operate the variables.
If we know how to operate it at first glance,

it saves time from tracing or running.
(Yeah, I copied it from the type hint.)
Map
users
A dict? What are the key and the value?
uid_user_map

uid_user_map['mosky'] # -> User('mosky')
# ok

users = {

'mosky': User('mosky'),

…

}
# even better

uid_user_map = {

'mosky': User('mosky'),

…

}
Tuple
uid, name = uid_name_pair
a, b, c = a_b_c_tuple
key_value_pairs = sql('select key, value')
for key, value in key_value_pairs:

…
key_value_map = dict(key_value_pairs)
Composite
If apply structure hint and type hint,
It will be long.
You may shorten.
Keep long description in comment or doc.
Use common abbreviation
http://abbreviations.com/
Use acronym, e.g., rlname for really_long_name.
Do comment if you use them.
# compromise between meaning and length

#

# event key: e.g., 'monthers_day'

# config_d: config dict

#

# - start_date: …

# …

#

event_key_config_d_map = {

'monthers_day': {…}

}
# focus on reducing length

#

# ekey: event key

# config: config dict

#

# - start_date: …

# …

#

ekey_config_map = {

'monthers_day': {…}

}
adj. new_user
past participle joined_date
present participle working_queue
innitive keys_to_remove
another noun template_args
int
n, m

i, j, k

twd_int
int/range
page_no

birth_month

birth_day
tids_idx
bool
new, joined

user_is_new

new_or_not

new_bool
str name, month_str
str/key event_key
str/url next_url
str / json user_json
str/html page_html
str/sql to_update_sql
dict user_d, user_dict
list uids, uid_list
set uid_set
mapping uid_user_map
generator uid_gen
date start_date
datetime joined_dt
re email_re
decimal total_dec
currency
total_currency, total_ccy

total_twd
key → value uid_user_d_map
(x, y) uid_user_pair
[(x, y), …] uid_user_pairs
(x, y, z) uid_nick_email_tuple
Return Type Hint
We operate the variables.
If we know how to operate it at first glance,

it saves time from tracing or running.
(Yeah, I copied it from type hint, again.)
.parse
What we will get?
.parse_to_tree
.allow_to_log_in
Allow something to log in?
.do_allow_to_log_in
If return value is a bool, use yes–no question.
Performance Hint
get_name # Memory op.
parse_from_json # CPU op.
query_html

request_html # IO op.
Let reader know the roughy cost.
Private Hint
“Don't touch me hint”
A simple underscore prex (_)
Don't use me out of the module or le.
Non-privates are just public APIs.
Hints
Type Hint
Structure Hint
Return Type Hint
Performance Hint
Private Hint
A random line now is more understandable.
Blank Line
Blank Line
Use blank line to separate your code into:
Paragraph
Section
Like lightweight markup language,

e.g., Markdown, RST.
Paragraph
Lines without any blank line.
Group similar lines into a paragraph.
Contains sub-paragraph.
Use blank line to separate paragraphs.
try:

html = read_html_from_cache(url)

except IOError:

html = request_html(url)
Section
Paragraphs.
Group similar paragraphs into a section.
Avoid sub-section.
Use two blank lines to separate sections.
<section A's paragraph 1>



<section A's paragraph 2>





<section B's paragraph 1>



…
Still don't understand?

Try to read a paragraph, then a section.
The “Lines”
Dependency
The F function calls the G function.
F depends on G.
F → G
It's a “Line”.
How messy?
Are the directions are all same?
Usually ↑ in a file and files.
Order your code.
Are they point to limited sections or a les?
Lesser is better.
Section or modularize them.
At least, easier to trace.
Bad Smell
Reality
Don't have time to refactor.
They actually work well.
Make you itch, but won't beat you.
You may already understand.
So Just Seal It Off
Comment the pitfalls.
Use #TODO rather than really refactor.
Assign return value to a better named variable.
Wrap them.
Just write new code.
Stay focused.
Recap
Recap
We read lines randomly.
Type hints and other hints
Paragraph & section by blank line.
Line your functions.
Bad smell won't beat you.
http://mosky.tw

More Related Content

PDF
Boost Maintainability
PDF
Elegant concurrency
PDF
Memory Management In Python The Basics
PDF
Programming with Python - Adv.
PDF
Python: an introduction for PHP webdevelopers
ODP
Dynamic Python
PDF
Elegant Solutions For Everyday Python Problems - Nina Zakharenko
PDF
Writing and using php streams and sockets tek11
Boost Maintainability
Elegant concurrency
Memory Management In Python The Basics
Programming with Python - Adv.
Python: an introduction for PHP webdevelopers
Dynamic Python
Elegant Solutions For Everyday Python Problems - Nina Zakharenko
Writing and using php streams and sockets tek11

What's hot (20)

PDF
Create your own PHP extension, step by step - phpDay 2012 Verona
PDF
Building Custom PHP Extensions
PPTX
Php Extensions for Dummies
PPT
Groovy presentation
PDF
Understanding PHP objects
PDF
PHP7 is coming
PPTX
Streams, sockets and filters oh my!
PDF
Php and threads ZTS
PDF
PyCon 2013 : Scripting to PyPi to GitHub and More
PDF
Gcrc talk
PDF
Why Python (for Statisticians)
PDF
Elegant Solutions For Everyday Python Problems - PyCon Canada 2017
PPTX
Php’s guts
PDF
Quick tour of PHP from inside
PDF
Profiling php5 to php7
PDF
Ruby for Java Developers
PPT
Hacking with hhvm
PDF
Elegant Solutions for Everyday Python Problems Pycon 2018 - Nina Zakharenko
PDF
Php7 extensions workshop
PDF
PHP 7 OPCache extension review
Create your own PHP extension, step by step - phpDay 2012 Verona
Building Custom PHP Extensions
Php Extensions for Dummies
Groovy presentation
Understanding PHP objects
PHP7 is coming
Streams, sockets and filters oh my!
Php and threads ZTS
PyCon 2013 : Scripting to PyPi to GitHub and More
Gcrc talk
Why Python (for Statisticians)
Elegant Solutions For Everyday Python Problems - PyCon Canada 2017
Php’s guts
Quick tour of PHP from inside
Profiling php5 to php7
Ruby for Java Developers
Hacking with hhvm
Elegant Solutions for Everyday Python Problems Pycon 2018 - Nina Zakharenko
Php7 extensions workshop
PHP 7 OPCache extension review
Ad

Viewers also liked (19)

PDF
Simple Belief - Mosky @ TEDxNTUST 2015
PDF
Concurrency in Python
PDF
ZIPCodeTW: Find Taiwan ZIP Code by Address Fuzzily
PDF
Learning Git with Workflows
PDF
Graph-Tool in Practice
PDF
Learning Python from Data
PDF
Programming with Python - Basic
PDF
Cython - close to metal Python
PDF
10 governments that went bankrupt
PDF
Minimal MVC in JavaScript
PDF
Introduction to Clime
PDF
Pycon UA 2016
PDF
Multiprocessing with python
PPT
How to Present Like a Pro – Part I
PPTX
Slack presentation
 
PDF
Object-oriented Programming in Python
PDF
Consensus 2015 - State of Blockchain
PDF
The True Timeline Behind The People vs. O.J. Simpson
PDF
Lawyers and Social Media in 2016
Simple Belief - Mosky @ TEDxNTUST 2015
Concurrency in Python
ZIPCodeTW: Find Taiwan ZIP Code by Address Fuzzily
Learning Git with Workflows
Graph-Tool in Practice
Learning Python from Data
Programming with Python - Basic
Cython - close to metal Python
10 governments that went bankrupt
Minimal MVC in JavaScript
Introduction to Clime
Pycon UA 2016
Multiprocessing with python
How to Present Like a Pro – Part I
Slack presentation
 
Object-oriented Programming in Python
Consensus 2015 - State of Blockchain
The True Timeline Behind The People vs. O.J. Simpson
Lawyers and Social Media in 2016
Ad

Similar to Beyond the Style Guides (20)

PPT
Láş­p trĂŹnh C
PDF
Notes1
 
PDF
ACM init() Spring 2015 Day 1
PDF
Lotusphere 2007 AD505 DevBlast 30 LotusScript Tips
PDF
A Bonus to the "Three Interviews About Static Analyzers" Article, or Intervie...
PDF
Python for scientific computing
PDF
An SEO’s Intro to Web Dev PHP
PPT
Php, mysq lpart1
PDF
The Sieve of Eratosthenes - Part 1
PDF
The Sieve of Eratosthenes - Part 1 - with minor corrections
PDF
Boo Manifesto
PPT
Learn python
PDF
A gentle introduction to algorithm complexity analysis
PDF
Basics of Programming - A Review Guide
PPTX
Chapter 1-Introduction and syntax of python programming.pptx
PDF
You should Know, What are the Common mistakes a node js developer makes?
PDF
Ad505 dev blast
PDF
lab4_php
PDF
lab4_php
PPTX
Python_Introduction&DataType.pptx
Láş­p trĂŹnh C
Notes1
 
ACM init() Spring 2015 Day 1
Lotusphere 2007 AD505 DevBlast 30 LotusScript Tips
A Bonus to the "Three Interviews About Static Analyzers" Article, or Intervie...
Python for scientific computing
An SEO’s Intro to Web Dev PHP
Php, mysq lpart1
The Sieve of Eratosthenes - Part 1
The Sieve of Eratosthenes - Part 1 - with minor corrections
Boo Manifesto
Learn python
A gentle introduction to algorithm complexity analysis
Basics of Programming - A Review Guide
Chapter 1-Introduction and syntax of python programming.pptx
You should Know, What are the Common mistakes a node js developer makes?
Ad505 dev blast
lab4_php
lab4_php
Python_Introduction&DataType.pptx

More from Mosky Liu (7)

PDF
Statistical Regression With Python
PDF
Practicing Python 3
PDF
Data Science With Python
PDF
Hypothesis Testing With Python
PDF
Dive into Pinkoi 2013
PDF
MoSQL: More than SQL, but Less than ORM @ PyCon APAC 2013
PDF
MoSQL: More than SQL, but less than ORM
Statistical Regression With Python
Practicing Python 3
Data Science With Python
Hypothesis Testing With Python
Dive into Pinkoi 2013
MoSQL: More than SQL, but Less than ORM @ PyCon APAC 2013
MoSQL: More than SQL, but less than ORM

Recently uploaded (20)

PDF
medical staffing services at VALiNTRY
PPTX
AMADEUS TRAVEL AGENT SOFTWARE | AMADEUS TICKETING SYSTEM
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by AndrĂŠ Kraus
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PDF
17 Powerful Integrations Your Next-Gen MLM Software Needs
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PPTX
Advanced SystemCare Ultimate Crack + Portable (2025)
PPTX
Patient Appointment Booking in Odoo with online payment
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PDF
Autodesk AutoCAD Crack Free Download 2025
PDF
Complete Guide to Website Development in Malaysia for SMEs
PDF
Tally Prime Crack Download New Version 5.1 [2025] (License Key Free
PDF
Product Update: Alluxio AI 3.7 Now with Sub-Millisecond Latency
PPTX
Transform Your Business with a Software ERP System
PDF
wealthsignaloriginal-com-DS-text-... (1).pdf
PDF
Nekopoi APK 2025 free lastest update
PDF
Download FL Studio Crack Latest version 2025 ?
PPTX
Computer Software and OS of computer science of grade 11.pptx
PDF
Salesforce Agentforce AI Implementation.pdf
medical staffing services at VALiNTRY
AMADEUS TRAVEL AGENT SOFTWARE | AMADEUS TICKETING SYSTEM
T3DD25 TYPO3 Content Blocks - Deep Dive by AndrĂŠ Kraus
Odoo Companies in India – Driving Business Transformation.pdf
17 Powerful Integrations Your Next-Gen MLM Software Needs
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
Advanced SystemCare Ultimate Crack + Portable (2025)
Patient Appointment Booking in Odoo with online payment
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
How to Choose the Right IT Partner for Your Business in Malaysia
Autodesk AutoCAD Crack Free Download 2025
Complete Guide to Website Development in Malaysia for SMEs
Tally Prime Crack Download New Version 5.1 [2025] (License Key Free
Product Update: Alluxio AI 3.7 Now with Sub-Millisecond Latency
Transform Your Business with a Software ERP System
wealthsignaloriginal-com-DS-text-... (1).pdf
Nekopoi APK 2025 free lastest update
Download FL Studio Crack Latest version 2025 ?
Computer Software and OS of computer science of grade 11.pptx
Salesforce Agentforce AI Implementation.pdf

Beyond the Style Guides