zoukankan      html  css  js  c++  java
  • IPython中也要保持优雅(DRY原则)

    What is IPython?

    IPython provides a rich architecture for interactive computing with:

    • A powerful interactive shell.
    • A kernel for Jupyter.
    • Support for interactive data visualization and use of GUI toolkits.
    • Flexible, embeddable interpreters to load into your own projects.
    • Easy to use, high performance tools for parallel computing.

    这是官网给出的解释,总结来说IPython是建立在python解释器基础上的一款交互shell,相对与基础的python shell,它提供更加方便的交互能力,比如:Tab补全、方便编写func等等。而且IPython也作为Jupyter的内核,支持并行计算等等。可以说:“用过的都说好~”
    安装方法

    $pip install ipython
    

    启动方法

    $ipython
    

    保持优雅(DRY原则)

    据统计,工作中,我在IPython中输入最多的5行代码:

    In [1]: import json
    In [2]: from pprint import pprint
    In [3]: true = True
    In [4]: false = False
    In [5]: null = None
    

    也就是说每次进入IPython,我都需要先输入这个5行代码,以便我能在后面处理实际问题时不卡可,这要花费我5s的时间(也许手速快的人3s就能搞定),无论如何,都是不DRY

    从一个py文件中导入

    最开始想到的是将这些常用代码都放在一个py文件中,然后在IPython中只要导入这个文件即可,像这样:

    编写一个init.py文件

    import json
    from pprint import pprint
    true = True
    false = False
    null = None
    

    在IPython中只要导入

    In [1]: from init import *
    In [2]: pprint(ture)
    True
    

    这样就从原本要写5行量变成了1行,这样手速快和手速慢的人之间就没多大差距了

    这个已经很DRY了,那有没有更DRY的原则?

    你听说过IPython中的startup吗

    更DRY的原则???
    那不就是变成0行?

    先科普一下,startup是一个文件夹(它的全路径长这样~/.ipython/profile_default/startup),进入文件可以看到里面有一个README:

    This is the IPython startup directory
    
    .py and .ipy files in this directory will be run *prior* to any code or files specified
    via the exec_lines or exec_files configurables whenever you load this profile.
    
    Files will be run in lexicographical order, so you can control the execution order of files
    with a prefix, e.g.::
    
        00-first.py
        50-middle.py
        99-last.ipy
    

    也就是说我们如果把之前编写的init.py文件放到这个目录下,它就会在启动IPython时自动执行

    $mv init.py ~/.ipython/profile_default/startup
    

    然后再试试

    In [1]: pprint(ture)
    True
    

    It's work! 这下就很DRY了,我以后每次使用IPython都会比原来节约5s时间,时间管理大师~

  • 相关阅读:
    Skimage=scikit-image SciKit 包的模块(转载)
    python day12
    python day11
    python day10
    python day9
    python day8
    python day7
    python day6
    python 第五天
    python 第四天
  • 原文地址:https://www.cnblogs.com/Zioyi/p/15054902.html
Copyright © 2011-2022 走看看