Skip to content

Instantly share code, notes, and snippets.

@elcolie
Created September 10, 2019 07:13
Show Gist options
  • Save elcolie/21f983952d93c3e7b374420323a95aee to your computer and use it in GitHub Desktop.
Save elcolie/21f983952d93c3e7b374420323a95aee to your computer and use it in GitHub Desktop.

Styling

Python supports many programmer from variety of programming background. Therefore you might found some style adopted from others programming languages

Here are some of style that I recommend everybody follow

  1. print(f"var: {var}"). Use literal string interpolation
  2. logger.info. User Python logger module do not use print
  3. def mtl_request(data: typing.Dict, headers: typing.Dict, endpoint: str = 'DOPA'): Add type hint
  4. Avoid if else use key: value from dict
  5. with to deal with file
  6. single quote for programming, double quote for human string
  7. hyphen in the url
  8. Use absolute header. Not relative path

Django

  1. Do not expose Django Admin to any people except programmer
  2. ForeignKey, M2M. Always add related_names, related_query_names
  3. Keep app flat not nested

Django REST

  1. Always validate input with validator
  • They are 3 options
  • Default
  • validator
  • def validate() DO NOT use .save(**kwargs) when it is not necessity
from rest_framework import serializers
class ExampleSerializer(serializers.ModelSerializer):
    var_default = serializers.IntegerField() # Use default validator
    var1 = serializers.CharField(validators=[validator1, validator2])
    var2 = serializers.EmailField()

    def validate(self, attrs):
        # customized logic here
        return attrs

Miscellaneous

  1. ngrok to debug your webhook
  2. import ipdb; ipdb.set_trace() is better than pdb

References:

pyguide
PEP8
python-guide

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment