Hidden features of Python

What are the lesser-known but useful features of the Python programming language?

  • Try to limit answers to Python core.
  • One feature per answer.
  • Give an example and short description of the feature, not just a link to documentation.
  • Label the feature using a title as the first line.
  • Quick links to answers:

  • Argument Unpacking
  • Braces
  • Chaining Comparison Operators
  • Decorators
  • Default Argument Gotchas / Dangers of Mutable Default arguments
  • Descriptors
  • Dictionary default .get value
  • Docstring Tests
  • Ellipsis Slicing Syntax
  • Enumeration
  • For/else
  • Function as iter() argument
  • Generator expressions
  • import this
  • In Place Value Swapping
  • List stepping
  • __missing__ items
  • Multi-line Regex
  • Named string formatting
  • Nested list/generator comprehensions
  • New types at runtime
  • .pth files
  • ROT13 Encoding
  • Regex Debugging
  • Sending to Generators
  • Tab Completion in Interactive Interpreter
  • Ternary Expression
  • try/except/else
  • Unpacking+ print() function
  • with statement

  • Metaclasses

    of course :-) What is a metaclass in Python?


    I personally love the 3 different quotes

    str = "I'm a string 'but still I can use quotes' inside myself!"
    str = """ For some messy multi line strings.
    Such as
    <html>
    <head> ... </head>"""
    

    Also cool: not having to escape regular expressions, avoiding horrible backslash salad by using raw strings :

    str2 = r"n" 
    print str2
    >> n
    

    Generators

    I think that a lot of beginning Python developers pass over generators without really grasping what they're for or getting any sense of their power. It wasn't until I read David M. Beazley's PyCon presentation on generators (it's available here) that I realized how useful (essential, really) they are. That presentation illuminated what was for me an entirely new way of programming, and I recommend it to anyone who doesn't have a deep understanding of generators.

    链接地址: http://www.djcxy.com/p/7414.html

    上一篇: 整数空值

    下一篇: Python的隐藏功能