Splat and Double Splat
Lesson 24 of 48 in Coddy's Python for Ruby Developers course.
Ruby and Python both use a star to gather extra positional arguments and two stars for keyword arguments. Python gathers positional extras into a tuple, not a Ruby array. Keyword extras become a dict. At a call site, a star expands an iterable into positional arguments, and two stars expand a mapping with string keys into keyword arguments. A literal dictionary is still one positional argument unless you explicitly expand it. This is especially important when leaving older Ruby APIs that treated a final hash as options. Read the Python signature to decide whether to pass a dictionary or keyword arguments.
Ruby
def total(*values, **options)
values.sum * options.fetch(:factor, 1)
end
puts total(2, 3, factor: 2)Python
def total(*values, **options):
print(type(values).__name__)
return sum(values) * options.get('factor', 1)
print(total(*[2, 3], **{'factor': 2}))Porting trap
Do not depend on Ruby-version-specific final-hash conversion rules in Python. Use explicit keyword arguments or explicit double-star expansion.
Challenge
BeginnerImplement scaled_total(*values, **options). All values are integers. Return their sum multiplied by options.get("factor", 1). Ignore other option names. Do not mutate collections or print. The driver reads a line of integer tokens (possibly empty) and a factor on the next line. It prints a call with only unpacked values, then a call with unpacked values and a dictionary containing the factor.
Your function definitions go in functions.py. The locked driver.py imports them and handles the supplied input/output and checks. You do not need to edit the driver.
Try it yourself
from functions import scaled_total
values = [int(part) for part in input().split()]
factor = int(input())
print(scaled_total(*values))
print(scaled_total(*values, **{"factor": factor, "note": "ignored"}))
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Python for Ruby Developers
1From Ruby to Python
Run Your First Python ProgramStrings and InterpolationNames and Mutable StringsDivision and ParsingFrom end to IndentationRecap: Rewrite a Receipt4Iteration and Transformations
each and Python foreach_pair and enumeratenext Becomes continueselect, map, and sort_byRecap: Build a Ranking2Values and Decisions
nil Becomes None== and equal?Zero Is False in Pythonelsif and Conditional ValuesRecap: Eligibility Rules5Functions and Closures
Explicit Return ValuesDefaults Run at DefinitionSplat and Double SplatBlocks Become CallablesRecap: Refactor a Pricing Tool3Collections and References
Array Methods and ListsParallel Assignment and TuplesHash Defaults and Dict Keysdup, Copies, and SetsRecap: Clean an Inventory6Reliable Python Programs
gets, input, and Formattingrescue and Context Managersrequire and Import GuardsHints Do Not Enforce TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler