title: Optional argument in command with click
body: <p>I am trying to accomplish something not very standard for CLI parsing with Click and it only works partially:</p>
  
  <ul>
  <li>main CLI has multiple sub-commands (in sample below 'show' and 'check')</li>
  <li>both those commands might have optional argument, but the argument is preceding them not following</li>
  <li>I decided to handle that argument in the group "above" it and pass the value in the context</li>
  </ul>
  
  <p>Sample:</p>
  
  <pre><code>import click
  
  @click.group()
  @click.argument('hostname', required=False)
  @click.pass_context
  def cli(ctx, hostname=None):
      """"""
      ctx.obj = hostname
      click.echo("cli: hostname={}".format(hostname))
  
  @cli.command()
  @click.pass_obj
  def check(hostname):
      click.echo("check: hostname={}".format(hostname))
  
  @cli.command()
  @click.pass_obj
  def show(hostname):
      click.echo("check: hostname={}".format(hostname))
  
  if __name__ == '__main__':
      cli()
  </code></pre>
  
  <p>The part WITH the hostname works:</p>
  
  <pre><code>&gt; pipenv run python cli.py  localhost check
  cli: hostname=localhost
  check: hostname=localhost
  &gt; pipenv run python cli.py  localhost show
  cli: hostname=localhost
  check: hostname=localhost
  </code></pre>
  
  <p>But the part WITHOUT the hostname DOES NOT:</p>
  
  <pre><code>&gt; pipenv run python cli.py show
  Usage: cli.py [OPTIONS] [HOSTNAME] COMMAND [ARGS]...
  
  Error: Missing command.
  </code></pre>
  
  <p>Anybody has an idea about the direction I should start looking into?</p>