MongoEngine / MongoEngine/mongoengine

ListField(FloatField) does not allow NoneType values

Open
#2,290 8 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
4.3k
Forks
1.2k
Avg merge
4h 41m
Merged PRs (30d)
11

Description

I recently had an issue when converting a field from IntField to FloatField. The default value for the field is None and when we tried to use FloatField we were getting a TypeError: float() argument must be a string or a number, not 'NoneType'.

I've tracked it down to this line of code only catching ValueError exceptions while in IntField it also catches the TypeError.

As a temporary workaround I've created my own class that also catches the TypeError and allows me to use None as a value for floats:

class CustomFloatField(FloatField):
    """Floating point number field. Added TypeError check to allow NoneType values"""
    def to_python(self, value):
        try:
            value = super().to_python(value)
        except TypeError:
            pass
        return value

I'm posting this issue to ask if there is a specific reason behind FloatFields not accepting None values because then my custom field might cause me issues down the road or was it just an oversight?

If there isn't a specific reason I'd be happy to contribute a PR that adds it.

Mongoengine version: 0.19.1
Python version: 3.7.5

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

The behavior is in mongoengine/fields.py at the FloatField conversion line linked in the issue. Compare it with IntField's exception handling, verify the expected None behavior, and add coverage for the reported TypeError before confirming the field accepts None.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
databases
Issue type
Bug
Difficulty
1/5
Estimated time
Under an hour
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.