Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Special Singleton (like None) [duplicate]

Tags:

python

How would I go about making a special singleton, like None? (I'm new to python.)

I want to be able to do this sort of thing:

def create_mutations(d):
    return [
        Mutation(c, v)
        if v is not CellAction.Delete else
        Mutation(c, isDelete=True)
        for (c, v) in d
        ]

Used like this:

create_mutations({'a': 5, 'b': None, 'c': CellAction.Delete})

This would create a list containing three mutations, meaning "set a to 5, set b to None, and delete c."

The point is that in the definition of create_mutations I cannot use ... if v is not None else ... because then there is no distinction between "set b to None" and "delete b."

I can clarify if the question isn't clear.

like image 776
Timothy Shields Avatar asked Jun 13 '26 15:06

Timothy Shields


2 Answers

You can just instantiate an object somewhere in your module or class like this:

Delete = object()

This is enough for most cases.

like image 167
Michael Avatar answered Jun 15 '26 07:06

Michael


Simply make some object and give it a name. An empty class will do:

class Delete:
    pass

Or, as Michael notes, an object instance.

Whatever object you use should be mutable if you plan to test for it using is; Python has a habit of sharing instances of immutable objects. (For example, all empty tuples are the same object.)

like image 25
kindall Avatar answered Jun 15 '26 07:06

kindall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!