Storing code inside a dictionary
Question: I'm getting into Python, and though of writing my own script which allows me
to check arguments provided when a program is run. An example below of what
I'm trying to achieve:

`python file.py -v -h anotherfile.py`  
or  
`./file.py -v -h anotherfile.py`

In these two cases, the `-v` and `-h` arguments, print out the module version,
and a basic help file. I already have the code to differentiate between
arguments and files, except I want to create a generalised module on the
matter.

The following code written in Java-

    
    
    // Somewhere.
    public static HashMap<String, Runnable> args = new HashMap<String, Runnable>();
    public void addArgument(String argument, Runnable command) {
        if (argument.length() > 0) {
            if (args.get(argument) == null) {
                args.put(argument, command);
            } else {
                System.err.println("Cannot add argument: " + argument + " to HashMap as the mapping already exists.");
                // Recover.
            }
        }
    }
    
    // Somewhere else.
    foo.addArgument("-v", () -> {System.out.println("version 1.0");});
    foo.args.get("-v").run();
    

-will run the Lambda Expressions _(atleast that's what I read they were when researching the topic)_ successfully. I have no idea how Lambda Expressions work however, and have only basic knowledge of using them.

**The point of this question, is how can I implement something like the Java
example, in Python, storing any type of code inside of an array?**

The thing is with the Java example though, if I have `int i = 0;` defined in
the class which executes `addArgument` and uses `i` somehow or rather, the
class containing `addArgument` knows to use `i` from the one that invoked it.
I'm worried that this may not be the same case for Python...

I want to be able to store them in dictionaries, or some other sort of key-
based array, so I can store them in the following manner:

    
    
    # Very rough example on the latter argument, showing what I'm after.
    addoption("-v", print("version 1.0"))
    

**EDIT: Example of what I want: (not working as is) (please ignore the ;'s)**

    
    
    args = {};
    
    def add(argument, command):
        args[argument] = lambda: command;  # Same problem when removing 'lambda:'
    
    def run():
        for arg in args:
            arg();  # Causing problems.
    
    def prnt():
        print("test");
    
    add("-v", prnt);
    run();
    


Answer: EDIT: to correct your most recent code, iterating over a dictionary yields its
keys not its values, so you need:

    
    
    args = {};
    
    def add(argument, command):
        args[argument] = command;
    
    def run():
        for arg in args:
            args[arg]()     # <<<<<<<<<<
    
    def prnt():
        print("test");
    
    add("-v", prnt);
    run();
    

For the example you give, a dictionary of functions, although possible, isn't
really the natural way to go about things in Python. The standard library has
a module, [`argparse`](https://docs.python.org/3/library/argparse.html)
specifically for dealing with all things commmand-line argument related, and
rather than using keys to a dictionary you can parse the command line
arguments and refer to their stored constants.

    
    
    import argparse
    
    def output_version():
        print('Version 1.0!')
    
    parser = argparse.ArgumentParser(description="A program to do something.")
    parser.add_argument('-v', help='Output version number.', action='store_true')
    
    args = parser.parse_args()
    if args.v:
        output_version()
    

(In fact outputting a version string is also handled natively by `argparse`:
see [here](https://docs.python.org/3/library/argparse.html#action)).

To print out the contents of a text file, `myfile.txt` when the `-p` switch is
given:

    
    
    import argparse
    
    def print_file(filename):
        with open(filename) as fi:
            print(fi.read())
    
    parser = argparse.ArgumentParser(description="A program to do something.")
    parser.add_argument('-p', help='Print a plain file.', action='store')
    
    args = parser.parse_args()
    
    if args.p:
        print_file(args.p)
    

Use with e.g.

    
    
    $ prog.py -p the_filename.txt
    

