argparse argument order

To keep arguments ordered, I use a custom action like this: import argparse class CustomAction(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): if not ‘ordered_args’ in namespace: setattr(namespace, ‘ordered_args’, []) previous = namespace.ordered_args previous.append((self.dest, values)) setattr(namespace, ‘ordered_args’, previous) parser = argparse.ArgumentParser() parser.add_argument(‘–test1’, action=CustomAction) parser.add_argument(‘–test2’, action=CustomAction) To use it, for example: >>> parser.parse_args([‘–test2’, ‘2’, ‘–test1’, ‘1’]) Namespace(ordered_args=[(‘test2’, … Read more

Passing a list of kwargs?

Yes. You do it like this: def method(**kwargs): print kwargs keywords = {‘keyword1’: ‘foo’, ‘keyword2’: ‘bar’} method(keyword1=’foo’, keyword2=’bar’) method(**keywords) Running this in Python confirms these produce identical results: {‘keyword2’: ‘bar’, ‘keyword1’: ‘foo’} {‘keyword2’: ‘bar’, ‘keyword1’: ‘foo’}

Calling a Python function with *args,**kwargs and optional / default arguments

You can do that in Python 3. def func(a,b,*args,kw1=None,**kwargs): The bare * is only used when you want to specify keyword only arguments without accepting a variable number of positional arguments with *args. You don’t use two *s. To quote from the grammar, in Python 2, you have parameter_list ::= (defparameter “,”)* ( “*” identifier … Read more

How to increase/reduce the fontsize of x and y tick labels

You can set the fontsize directly in the call to set_xticklabels and set_yticklabels (as noted in previous answers). This will only affect one Axes at a time. ax.set_xticklabels(x_ticks, rotation=0, fontsize=8) ax.set_yticklabels(y_ticks, rotation=0, fontsize=8) Note this method should only be used if you are fixing the positions of the ticks first (e.g. using ax.set_xticks). If you … Read more

Proper way to use **kwargs in Python

You can pass a default value to get() for keys that are not in the dictionary: self.val2 = kwargs.get(‘val2’,”default value”) However, if you plan on using a particular argument with a particular default value, why not use named arguments in the first place? def __init__(self, val2=”default value”, **kwargs):

What is the purpose and use of **kwargs? [duplicate]

You can use **kwargs to let your functions take an arbitrary number of keyword arguments (“kwargs” means “keyword arguments”): >>> def print_keyword_args(**kwargs): … # kwargs is a dict of the keyword args passed to the function … for key, value in kwargs.iteritems(): … print “%s = %s” % (key, value) … >>> print_keyword_args(first_name=”John”, last_name=”Doe”) first_name … Read more