[New Concept Exercise]: Functions in Python
See original GitHub issueThis issue describes how to implement the functions
concept exercise for the Python track.
There is an outdated issue for this exercise with some discussion. It can be found here
The related concept documents can be found here.
✅ Getting started
If you have not yet created or contributed to a concept exercise, this issue will require some upfront reading to give you the needed background knowledge. Some good example exercises to look at in the repo:
💡Example Exercises💡 (click to expand)
We also recommend completing one or more of the concept exercises (they’re called “learning exercises”) on the website.
Please please read the docs before starting.
Posting PRs without reading these docs will be a lot more frustrating for you during the review cycle, and exhaust Exercism’s maintainers’ time. So, before diving into the implementation, please go through the following documents:
General Contributing Docs:
- Contributing to Exercism | Exercism and GitHub | - Contributor Pull Request Guide
- What are those Weird Task Tags about?
- Exercism Formatting and Style Guide
- Exercism Markdown Specification
- Reputation
Documents on Language Tracks and Concept Exercises
- Building Language Tracks: An Overview
- What are Concept Exercises?
- Concept Exercise Specifications
- Concept Exercise Stories
🎯 Goal
This functions
concept exercise is meant to teach a deeper understanding and use of functions
in Python. It should also explain how Python treats/views functions (as callable objects), and dig into some of the features that make Python functions
unique.
💡Learning objectives
- Understand more about Python
scopes
andnamespaces
- understand the difference between the
global
andnonlocal
keywords and when to use them
- understand the difference between the
- Get familiar with the special attributes of Python functions
- Get familiar with best practices when using
return
, and the difference between explicit and implicitreturn
- functions without an explicit return will return the singleton object
None
- functions without an explicit return will return the singleton object
- Understand what is meant by “functions are first class objects in Python”.
- understand that
functions
areobjects
in Python, and that they havetypes
- understand that
functions
can be assigned to variables, used in expressions, and stored in various data structures such asdicts
orlists
- create
functons
that are assigned to variables, used in expressions, and stored in different data structures. - understand and create
functions
that are/can be nested inside one another
- understand that
- Understand that Python considers a function a form of
callable object
. - Understand that a user-defined
function object
is created by afunction definition
.
🤔 Concepts
callable objects
first-class functions
global
nested functions
nonlocal
return
,implicit return
,explicit return
scope
- special
function attributes
🚫 Topics that are Out of scope
Concepts & Subjects that are Out of Scope (click to expand)
named parameters
(these can be touched on if needed)default parameters
(these can be touched on, if needed)arbitrary parameters
*args & **kwargs
keyword-only arguments
/
and*
for requiring parameter typesfunctions-as-arguments
(this can be mentioned, but shouldn’t be required for the exercise)functions-as-returns
(_this can be mentioned, but will be covered in-depth inhigher-order functions
)closures
(these will be covered in a different exercise)decorators
(these will be covered in a different exercise)functools.wraps
(this is used mostly for decorators)functools
(this will get its own exercise)comprehensions
generators
lambda
,anonymous functions
(these will be covered in a different exercise)recursion
↩️ Prerequisites
These are the concepts/concept exercises the student needs to complete/understand before solving this concept exercise. Since functions
is a “meta” topic, these will probably need to be adjusted to fit the parameters of the exercise.
Prereqs (click to expand)
basics
bools
comparisons
lists
list-methods
loops
numbers
strings
string-methods
📚 Resources for Writing and Reference
Resources (click to expand)
- Python Docs: Naming and Binding
- Python Docs: Python Scopes and Namespaces
- Python Docs: Defining Functions
- Function definitions (Python Library Reference)
- Dan Bader: Python s Functions are First-Class
- Real Python: Python Scope & the LEGB Rule
- Stack Overflow: Short Description of Python’s Scoping Rules?
- Real Python: Python Inner Functions: What are they Good For?
- Stack Abuse: How to Use global and nonlocal variables in Python
- The
nonlocal
Statement (Python Docs) - The
global
Statement (Python Docs) - Real Python: The Python return Statement: Usage and Best Practices
- Calls (Python Library Reference)
- Is it a Class or a Function? It’s a Callable! (Trey Hunner)
- Callables in Python (Vimal A.R Blog)
- Functions as Objects in Python – this is a subscription-based medium blog, so not good for hints or links
- Python Datamodel: Types
Exercise Ideas & Stories
Should you need inspiration for an exercise story, you can find a collection here. You can also port an exercise from another track, but please make sure to only to include tasks that actually make sense in Python and that add value for a student. Remove/replace/add tasks as needed to make the concept clear/workable.
📁 Exercise Files to Be Created
File Detail for this Exercise (click to collapse)
|
♾️ Exercise Metadata - Track
For more information on concept exercises and formatting for the Python track config.json
, please see config.json
. The track config.json
file can be found in the root of the Python repo.
You can use the below for the exercise UUID. You can also generate a new one via exercism configlet, uuidgenerator.net, or any other favorite method. The UUID must be a valid V4 UUID.
- Exercise UUID :
9f38f70d-48f4-4934-ae6e-d8277ede8edc
- concepts should be filled in from the Concepts section in this issue
- prerequisites should be filled in from the Prerequisites section in this issue
🎶 Implementation Notes
-
As a reminder, code in the
.meta/examplar.py
file should only use syntax & concepts introduced in this exercise or one of its prerequisite exercises. We run all ourexamplar.py
files through PyLint, but do not strictly require module docstrings. We do require function docstrings similar to PEP257. See this concept exerciseexemplar.py
for an example. -
Please do not use comprehensions, generator expressions, or other syntax not previously covered either in the introduction to this exercise, or to one of its prerequisites. Please also follow PEP8 guidelines.
-
In General, tests should be written using
unittest.TestCase
and the test file should be named<EXERCISE-NAME>_test.py
.- All asserts should contain a “user friendly” failure message (these will display on the webiste to students, so be as clear as you can).
- We use a
PyTest custom mark
to link test cases to exercise task numbers. - We also use
unittest.subtest
to parameterize test input where/when needed. Here is an example testfile that shows all three of these in action.
-
While we do use PyTest as our test runner and for some implementation tests, please check with a maintainer before using a PyTest-specific test method, fixture, or feature.
-
Our markdown and JSON files are checked against prettier . We recommend setting prettier up locally and running it prior to submitting your PR to avoid any CI errors.
🆘 Next Steps & Getting Help
If you'd like to work on this issue, comment saying "I'd like to work on this"
(there is no real need to wait for a response, just go ahead, we’ll assign you and put a[claimed]
label on the issue).- If you have any questions while implementing, please post the questions as comments in here, or contact one of the maintainers on our Slack channel.
Issue Analytics
- State:
- Created a year ago
- Comments:13 (13 by maintainers)
Top GitHub Comments
I won’t have time before this weekend I don’t think - but I am going to PR turning off the stale bot, since none of us on the track are moving very fast these days (which is OK!). Right now, if we comment on anything and 22 days pass, the critter wakes up and flags things as abandoned. It’s starting to not be useful, so. 😀
Apologies. Had some things to take care of this afternoon, so am late with replying to things.
I think for the exercise, it’s important to provide students the opportunity to practice using both
global
andnonlocal
in an appropriate or “safe” fashion (heavy guardrails). It doesn’t have to be elaborate, and it doesn’t have to be much more than a basic mimic (I am thinking of something similar to how we set up error handling messaging in a lot of practice exercises ).And I think for the instructions/introduction, it would be great to put cautions in, and examples of why it can be a bad idea. Although my thinking here is that if the task or tasks set up a “proper” or “good” use case, the students will more than likely find the foot-gun, and that will convey a really good lesson, about scope, using the keywords, AND about how the Python ethos is to say “we are all adults here, so you need to think through your choices, Python’s not going to do that for you.”
It does seem somewhat “unfair” to set up students like that … but I don’t know that we teach them fluency by hiding the warts of the language. While we do do that to some extent early on, by the time students are getting ready to feed functions to other functions, use recursion, nest functions, and all the other goodness that comes along with FP paradigms in Python, they should have a working sense of caution, and be building a sense of why endless mutability can be problematic.
So my thought is that maybe there is a task that has them reach out and modify/update a
global
constant. Or create aglobal
in a function that other functions could read/access (and modify at peril). I’m less clear on thenonlocal
, although that could be done with an inner function – and would be a quite legitimate (if minority) use-case.…and thinking out loud here… I don’t know if we want to consider a
mutability
topic, or if we want to (like we have with error handling) insert messages and reminders about the dangers of mutability as we build out the exercises in thefunctions
andhigher order functions
cluster … as well as theclasses
,class-customization
,class-interfaces
cluster.