Source From Here
Question
I have a variable, x, and I want to know whether it is pointing to a function or not:
How-To
If this is for Python 2.x or for Python 3.2+, you can also use callable(). It used to be deprecated, but is now undeprecated, so you can use it again. You can read the discussion here: http://bugs.python.org/issue10518. You can do this with:
If this is for Python 3.x but before 3.2, check if the object has a __call__ attribute. You can do this with:
The oft-suggested types.FunctionType approach is not correct because it fails to cover many cases that you would presumably want it to pass, like with builtins:
The proper way to check properties of duck-typed objects is to ask them if they quack, not to see if they fit in a duck-sized container. Don't use types.FunctionType unless you have a very specific idea of what a function is.
Supplement
* Python可調用對象 __call__ 方法的用法分析
This is a blog to track what I had learned and share knowledge with all who can take advantage of them
標籤
- [ 英文學習 ]
- [ 計算機概論 ]
- [ 深入雲計算 ]
- [ 雜七雜八 ]
- [ Algorithm in Java ]
- [ Data Structures with Java ]
- [ IR Class ]
- [ Java 文章收集 ]
- [ Java 代碼範本 ]
- [ Java 套件 ]
- [ JVM 應用 ]
- [ LFD Note ]
- [ MangoDB ]
- [ Math CC ]
- [ MongoDB ]
- [ MySQL 小學堂 ]
- [ Python 考題 ]
- [ Python 常見問題 ]
- [ Python 範例代碼 ]
- [心得扎記]
- [網路教學]
- [C 常見考題]
- [C 範例代碼]
- [C/C++ 範例代碼]
- [Intro Alg]
- [Java 代碼範本]
- [Java 套件]
- [Linux 小技巧]
- [Linux 小學堂]
- [Linux 命令]
- [ML In Action]
- [ML]
- [MLP]
- [Postgres]
- [Python 學習筆記]
- [Quick Python]
- [Software Engineering]
- [The python tutorial]
- 工具收集
- 設計模式
- 資料結構
- ActiveMQ In Action
- AI
- Algorithm
- Android
- Ansible
- AWS
- Big Data 研究
- C/C++
- C++
- CCDH
- CI/CD
- Coursera
- Database
- DB
- Design Pattern
- Device Driver Programming
- Docker
- Docker 工具
- Docker Practice
- Eclipse
- English Writing
- ExtJS 3.x
- FP
- Fraud Prevention
- FreeBSD
- GCC
- Git
- Git Pro
- GNU
- Golang
- Gradle
- Groovy
- Hadoop
- Hadoop. Hadoop Ecosystem
- Java
- Java Framework
- Java UI
- JavaIDE
- JavaScript
- Jenkins
- JFreeChart
- Kaggle
- Kali/Metasploit
- Keras
- KVM
- Learn Spark
- LeetCode
- Linux
- Lucene
- Math
- ML
- ML Udemy
- Mockito
- MPI
- Nachos
- Network
- NLP
- node js
- OO
- OpenCL
- OpenMP
- OSC
- OSGi
- Pandas
- Perl
- PostgreSQL
- Py DS
- Python
- Python 自製工具
- Python Std Library
- Python tools
- QEMU
- R
- Real Python
- RIA
- RTC
- Ruby
- Ruby Packages
- Scala
- ScalaIA
- SQLAlchemy
- TensorFlow
- Tools
- UML
- Unix
- Verilog
- Vmware
- Windows 技巧
- wxPython
2017年7月30日 星期日
2017年7月29日 星期六
[ Python 常見問題 ] argparse option for passing a list as option
Source From Here
Question
I am trying to pass a list as an argument to a command line program. Is there an argparse option to pass a list as option?
How-To
Use the nargs option or the append option (depending on how you want the user interface to behave).
nargs: The number of command-line arguments that should be consumed.
For example:
- test.py
Execution output:
action(append): This stores a list, and appends each argument value to the list.
For example:
- test_append.py
Execution output:
Notes. Don't use type=list!!! - There is probably no situation where you would want to use type=list with argparse. Ever.
Let's take a look in more detail at some of the different ways one might try to do this, and the end result.
- test_all.py
Here is the output you can expect:
Takeaways:
- Use nargs or action='append'
- Don't use type=list, as it will return a list of lists
Question
I am trying to pass a list as an argument to a command line program. Is there an argparse option to pass a list as option?
How-To
Use the nargs option or the append option (depending on how you want the user interface to behave).
nargs: The number of command-line arguments that should be consumed.
For example:
- test.py
- #!/usr/bin/env python3
- import argparse
- parser = argparse.ArgumentParser()
- # nargs='+' takes 1 or more arguments, nargs='*' takes zero or more.
- parser.add_argument('-l','--list', nargs='+', help='
Set flag' , required=True) - args = parser.parse_args()
- print("Given list: {}".format(args.list))
# ./test.py -l 1234 2345 3456 4567
Given list: ['1234', '2345', '3456', '4567']
action(append): This stores a list, and appends each argument value to the list.
For example:
- test_append.py
- #!/usr/bin/env python3
- import argparse
- parser = argparse.ArgumentParser()
- # This is useful to allow an option to be specified multiple times.
- parser.add_argument('-l','--list', action='append', help='
Set flag' , required=True) - args = parser.parse_args()
- print("Given list: {}".format(args.list))
# ./test_append.py -l 1234 -l 2345 -l 3456 -l 4567
Given list: ['1234', '2345', '3456', '4567']
Notes. Don't use type=list!!! - There is probably no situation where you would want to use type=list with argparse. Ever.
Let's take a look in more detail at some of the different ways one might try to do this, and the end result.
- test_all.py
- #!/usr/bin/env python3
- import argparse
- parser = argparse.ArgumentParser()
- # By default it will fail with multiple arguments.
- parser.add_argument('--default')
- # Telling the type to be a list will also fail for multiple arguments,
- # but give incorrect results for a single argument.
- parser.add_argument('--list-type', type=list)
- # This will allow you to provide multiple arguments, but you will get
- # a list of lists which is not desired.
- parser.add_argument('--list-type-nargs', type=list, nargs='+')
- # This is the correct way to handle accepting multiple arguments.
- # '+' == 1 or more.
- # '*' == 0 or more.
- # '?' == 0 or 1.
- # An int is an explicit number of arguments to accept.
- parser.add_argument('--nargs', nargs='+')
- # To make the input integers
- parser.add_argument('--nargs-int-type', nargs='+', type=int)
- # An alternate way to accept multiple inputs, but you must
- # provide the flag once per input. Of course, you can use
- # type=int here if you want.
- parser.add_argument('--append-action', action='append')
- # To show the results of the given option to screen.
- for _, value in parser.parse_args()._get_kwargs():
- if value is not None:
- print(value)
# ./test_all.py --default 1234 2345 3456 4567
usage: test_all.py [-h] [--default DEFAULT] [--list-type LIST_TYPE]
...
test_all.py: error: unrecognized arguments: 2345 3456 4567
# ./test_all.py --list-type 1234 2345 3456 4567
...
test_all.py: error: unrecognized arguments: --list-type 1234 2345 3456 4567
# ./test_all.py --list-type '1234 2345 3456 4567' // Quotes won't help here...
['1', '2', '3', '4', ' ', '2', '3', '4', '5', ' ', '3', '4', '5', '6', ' ', '4', '5', '6', '7']
# ./test_all.py --list-type-nargs 1234 2345 3456 4567
[['1', '2', '3', '4'], ['2', '3', '4', '5'], ['3', '4', '5', '6'], ['4', '5', '6', '7']]
# ./test_all.py --nargs 1234 2345 3456 4567
['1234', '2345', '3456', '4567']
# ./test_all.py --nargs-int-type 1234 2345 3456 4567
[1234, 2345, 3456, 4567]
# ./test_all.py --nargs-int-type -1234 2345 -3456 4567 // Negative numbers are handled perfectly fine out of the box.
[-1234, 2345, -3456, 4567]
# ./test_all.py --append-action 1234 --append-action 2345 --append-action 3456 --append-action 4567
['1234', '2345', '3456', '4567']
Takeaways:
- Use nargs or action='append'
nargs can be more straightforward from a user perspective, but it can be unintuitive if there are positional arguments because argparse can't tell what should be a positional argument and what belongs to the nargs; if you have positional arguments then action='append' may end up being a better choice. The above is only true if nargs is given '*', '+', or '?'. If you provide an integer number (such as 4) then there will be no problem mixing options with nargs and positional arguments because argparse will know exactly how many values to expect for the option.
- Don't use type=list, as it will return a list of lists
For request here, this option is not useful here. The unexpected result happens because under the hood argparse uses the value of type to coerce each individual given argument to your chosen type, not to aggregate of all arguments. Instead, You can use type=int (or whatever) to get a list of integers.
[ Python 常見問題 ] What is the difference between @staticmethod and @classmethod in Python?
Source From Here
Question
What is the difference between a function decorated with @staticmethod and one decorated with @classmethod?
How-To
Maybe a bit of example code will help: Notice the difference in the call signatures of foo, class_foo and static_foo:
Below is the usual way an object instance calls a method. The object instance, a, is implicitly passed as the first argument:
With classmethods, the class of the object instance is implicitly passed as the first argument instead of self:
You can also call class_foo using the class. In fact, if you define something to be a classmethod, it is probably because you intend to call it from the class rather than from a class instance. A.foo(1) would have raised a TypeError, but A.class_foo(1) works just fine:
One use people have found for class methods is to create inheritable alternative constructors.
With staticmethods, neither self (the object instance) nor cls (the class) is implicitly passed as the first argument. They behave like plain functions except that you can call them from an instance or the class:
Staticmethods are used to group functions which have some logical connection with a class to the class.
foo is just a function, but when you call a.foo you don't just get the function, you get a "partially applied" version of the function with the object instance a bound as the first argument to the function. foo expects 2 arguments, while a.foo only expects 1 argument. a is bound to foo. That is what is meant by the term "bound" below:
With a.class_foo, a is not bound to class_foo, rather the class A is bound to class_foo.
Here, with a staticmethod, even though it is a method, a.static_foo just returns a good 'ole function with no arguments bound. static_foo expects 1 argument, and a.static_foo expects 1 argument too.
Question
What is the difference between a function decorated with @staticmethod and one decorated with @classmethod?
How-To
Maybe a bit of example code will help: Notice the difference in the call signatures of foo, class_foo and static_foo:
- class A(object):
- def foo(self,x):
- print "executing foo(%s,%s)"%(self,x)
- @classmethod
- def class_foo(cls,x):
- print "executing class_foo(%s,%s)"%(cls,x)
- @staticmethod
- def static_foo(x):
- print "executing static_foo(%s)"%x
- a=A()
>>> a.foo(1)
executing foo(,1)
With classmethods, the class of the object instance is implicitly passed as the first argument instead of self:
>>> a.class_foo(1)
executing class_foo(,1)
You can also call class_foo using the class. In fact, if you define something to be a classmethod, it is probably because you intend to call it from the class rather than from a class instance. A.foo(1) would have raised a TypeError, but A.class_foo(1) works just fine:
>>> A.class_foo(1)
executing class_foo(,1)
One use people have found for class methods is to create inheritable alternative constructors.
With staticmethods, neither self (the object instance) nor cls (the class) is implicitly passed as the first argument. They behave like plain functions except that you can call them from an instance or the class:
>>> a.static_foo(1)
executing static_foo(1)
>>> A.static_foo(1)
executing static_foo(1)
Staticmethods are used to group functions which have some logical connection with a class to the class.
foo is just a function, but when you call a.foo you don't just get the function, you get a "partially applied" version of the function with the object instance a bound as the first argument to the function. foo expects 2 arguments, while a.foo only expects 1 argument. a is bound to foo. That is what is meant by the term "bound" below:
>>> print(a.foo)>
With a.class_foo, a is not bound to class_foo, rather the class A is bound to class_foo.
>>> print(a.class_foo)>
Here, with a staticmethod, even though it is a method, a.static_foo just returns a good 'ole function with no arguments bound. static_foo expects 1 argument, and a.static_foo expects 1 argument too.
>>> print(a.static_foo)
>>> print(A.static_foo)
2017年7月27日 星期四
[OO 設計模式] Gossip@DesignPattern : Behavioral - Chain of Responsibility 模式
轉載自 這裡
前言 :
如果您有一個應用程式,必須對輸入的字元作不同的處理,例如 :
使用結構化的方式,用 if..else 來判斷是否應處理,雖然直覺,壞處是如果要調整處理方式,例如要增加或減少處理方式、調整處理順序等,都必須對程式作出修改!
Chain of Responsibility 模式 :
您可以改為以下的方式 :
執行結果 :
在上例中,在每個特定處理器物件處理過後,可以決定是否交給下一個物件作處理(如果有的話),您可以自由設定下一個處理器,調整處理的順序等,而不用修改程式! 這是 Chain of Responsibility 模式的一個例子,多個物件都有機會處理請求,除了可以自由組合處理請求的物件之外,也可以避免請求的發送者與接收者之間的耦合關係,將這些物件組合為一個鏈,並沿著這個鏈傳遞該請求,每個物件都可以處理請求與決定是否傳遞給下一個處理物件.
在組織物件之間的職責時,通常是從細粒度至粗粒度的方式來組織,從特殊到抽象化,就像程式中將數字視為字元的特殊化,字元又為符號的特殊化. Chain of Responsibility 的 UML 結構圖如下所示 :
在更一般的情況下,可以將請求包裝為一個物件,並提供 getType() 之間的方法,以讓 Chain of Responsibility 中的物件進行比對,例如 :
在 Gof 的書中所舉的例子為輔助說明系統,在一個介面中希望使用者一定可以得到相關的說明主題,如果子元件有說明的話,就顯示相關說明,否則的話就轉發給 包括它的容器元件或父元件,以保證使用者的輔助說明請求一定可以得到回應.
Supplement
* Tutorialspoint - Chain of Responsibility Pattern
前言 :
如果您有一個應用程式,必須對輸入的字元作不同的處理,例如 :
- char c = 'A';
- if (Character.isLetter(c)) {
- System.out.println("處理字母資料");
- }
- if (Character.isDigit(c)) {
- System.out.println("處理數字資料");
- }
- System.out.println("處理符號資料");
Chain of Responsibility 模式 :
您可以改為以下的方式 :
- Handler.java : Handler 的抽象類別, 定義介面 API.
- package dp.behavior.chainofresp;
- public abstract class Handler {
- protected Handler next;
- Handler(Handler next) {
- this.next = next;
- }
- void doNext(char c) {
- if(next != null) {
- next.handle(c);
- }
- }
- abstract void handle(char c);
- }
- SymbolHandler.java : 處理 Symbol 的 Handler.
- package dp.behavior.chainofresp;
- public class SymbolHandler extends Handler {
- SymbolHandler(Handler next) {
- super(next);
- }
- void handle(char c) {
- System.out.printf("(%c)Symbol has been handled!\n", c);
- doNext(c);
- }
- }
- CharacterHandler.java : 處理 Char 的 Handler
- package dp.behavior.chainofresp;
- public class CharacterHandler extends Handler {
- CharacterHandler(Handler next) {
- super(next);
- }
- void handle(char c) {
- if(Character.isLetter(c)) {
- System.out.printf("\t(%c)Character has been handled!\n", c);
- }
- doNext(c);
- }
- }
- DigitHandler.java : 處理數字的 Handler
- package dp.behavior.chainofresp;
- public class DigitHandler extends Handler {
- DigitHandler(Handler next) {
- super(next);
- }
- void handle(char c) {
- if(Character.isDigit(c)) {
- System.out.printf("\t(%c)Digit has been handled!\n", c);
- }
- doNext(c);
- }
- }
- Main.java : 測試主類別
- package dp.behavior.chainofresp;
- public class Main {
- public static void main(String[] args) {
- Handler handler = new SymbolHandler(
- new CharacterHandler(
- new DigitHandler(null)));
- handler.handle('A');
- handler.handle('1');
- }
- }
執行結果 :
(A)Symbol has been handled!
(A)Character has been handled!
(1)Symbol has been handled!
(1)Digit has been handled!
在組織物件之間的職責時,通常是從細粒度至粗粒度的方式來組織,從特殊到抽象化,就像程式中將數字視為字元的特殊化,字元又為符號的特殊化. Chain of Responsibility 的 UML 結構圖如下所示 :
在更一般的情況下,可以將請求包裝為一個物件,並提供 getType() 之間的方法,以讓 Chain of Responsibility 中的物件進行比對,例如 :
- Request.java : 請求物件, 可以將請求包裝於此物件進行傳遞.
- package dp.behavior.chainofresp;
- public abstract class Request {
- private String type;
- Request(String type) { this.type=type; }
- String getType() { return type; }
- abstract void execute();
- }
- Handler.java : 新增處理 Request 物件的 API
- package dp.behavior.chainofresp;
- public abstract class Handler {
- protected Handler next;
- Handler(Handler next) {
- this.next = next;
- }
- void doNext(Request request)
- {
- if(next != null)
- {
- next.handle(request);
- }
- }
- void doNext(char c) {
- if(next != null)
- {
- next.handle(c);
- }
- }
- abstract void handle(Request request);
- abstract void handle(char c);
- }
- ConcreteHandler.java : 如果請求的類型是 "concrete" 則執行請求並停止 chain, 否則將該請求傳遞下去.
- package dp.behavior.chainofresp;
- public class ConcreteHandler extends Handler{
- ConcreteHandler(Handler next) {
- super(next);
- }
- @Override
- void handle(Request request) {
- if(request.getType().equals("concrete")) {
- request.execute();
- }
- else {
- doNext(request);
- }
- }
- @Override
- void handle(char c) {
- doNext(c);
- }
- }
在 Gof 的書中所舉的例子為輔助說明系統,在一個介面中希望使用者一定可以得到相關的說明主題,如果子元件有說明的話,就顯示相關說明,否則的話就轉發給 包括它的容器元件或父元件,以保證使用者的輔助說明請求一定可以得到回應.
Supplement
* Tutorialspoint - Chain of Responsibility Pattern
訂閱:
文章 (Atom)
[Git 常見問題] error: The following untracked working tree files would be overwritten by merge
Source From Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 # git clean -d -fx 方案2: 今天在服务器上 gi...
-
前言 : 為什麼程序管理這麼重要呢?這是因為: * 首先,本章一開始就談到的,我們在操作系統時的各項工作其實都是經過某個 PID 來達成的 (包括你的 bash 環境), 因此,能不能進行某項工作,就與該程序的權限有關了。 * 再來,如果您的 Linux 系統是個...
-
屬性 : 系統相關 - 檔案與目錄 語法 : du [參數] [檔案] 參數 | 功能 -a | 顯示目錄中個別檔案的大小 -b | 以bytes為單位顯示 -c | 顯示個別檔案大小與總和 -D | 顯示符號鏈結的來源檔大小 -h | Hum...
-
來源自 這裡 說明 : split 是 Perl 中非常有用的函式之一,它可以將一個字串分割並將之置於陣列中。若無特別的指定,該函式亦使用 RE 與 $_ 變數 語法 : * split /PATTERN/,EXPR,LIMIT * split /...