On Thu, Nov 11, 2021 at 10:06:45PM -0500, Ricky Teachey wrote:

> Is there a standard idiom-- perhaps using a type-hint-- to signal to the
> IDE/linter that my user-defined class is intended to be used as a
> function/factory, and not as a type (even though it is in fact a type)?

Not really. I don't think there is even a standard idiom for the human 
reader to decide whether something is used as a "function" or a "class". 
It is subjective, based on usage and convention. As others have pointed 
out, many functions in Python can be considered as class constructor:

     ord(number)  # constructs a string

even traditional functional programming, er, functions like map:

     map(func, iterable)  # returns a map object


I think that the best I can come up with is that if your class has a 
constructor that attaches input arguments (with or without additional 
processing) as attributes, then it might be considered "class-like". 
Something like this:

    class C:
        def __new__(cls, arg):
            obj = super().__new__(cls)
            obj.attribute = arg
            return obj

or equivalently:

    class C:
        def __init__(self, arg):
            self.attribute = arg

But if it looks like more this:

    class C:
        def __new__(cls, arg):
            obj = _convert(arg)  # possibly call a dunder method?
            return obj

then it is probably "function-like". But honestly, it's subjective. Some 
things feel like a transformation, conversion or cast using a function, 
and some things feel like constructing an object, even if it is 
impossible to find a hard, objective, bullet-proof distinction.


> Seems like if there were a standard idiom for telling the linter "this
> class is really just kind of a factory, don't complain about the
> lowercase", it might be kind of nice.

Any decent linter should have a switch to turn off a specific check for 
a line of code. For example, in flake8 the error code for class names is 
N801, so you should be able to disable that using:

    # noqa: N801

https://flake8.pycqa.org/en/3.1.1/user/ignoring-errors.html
https://github.com/PyCQA/pep8-naming



-- 
Steve
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/EOEJVSMTCI6TO5Q5LBTIGSYAGTJ773LN/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to