Python Forum
passing type choicr to function - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: General (https://python-forum.io/forum-1.html)
+--- Forum: News and Discussions (https://python-forum.io/forum-31.html)
+--- Thread: passing type choicr to function (/thread-34649.html)



passing type choicr to function - Skaperen - Aug-18-2021

in a function i am planning, one of the arguments is a type choice. i have used string names in the past such as 'str' or 'bytes'. i am thinking it would be simpler to just use the type's own class object as a reference, such as just str or bytes. what implications or issues might i run into by doing this? the function will never call the function passed to it. it will only compare references like if foo is str: or if foo in (bytes,bytearray):.


RE: passing type choicr to function - ndc85430 - Aug-21-2021

It's not really clear why you want to do this. Can you at least explain what this code is supposed to do, how you'd use it (test cases are great for that!), etc.?


RE: passing type choicr to function - Skaperen - Aug-22-2021

sorry for lack of code. this is just an idea i might apply to a project i am planning.

the purpose of the type argument in this and past projects is to request what type to give to data being created or obtained (from a file or a network). most often this is a limited choice such as str vs. bytes or maybe int vs. float. sometimes it is data to be passed somewhere, or stored somewhere, or returned to the caller.

code might look like:
    getdata(whatiswanted,'bytes')
but with this new idea it would be:
    getdata(whatiswanted,bytes)
the function being called could handle it by comparison like
    if typewanted is str:
        ... # code to handle str goes here
    elif typewanted is bytes:
        ... # code to handle bytes goes here
   else:
        raise ... # code to describe caller error here
it is rarely practical to call the type as a function but it could be done after it is validated as an expected type. i did so once when bytes and bytearray were the valid types. it could be done in a few other cases i could imagine.

one advantage to this idea is that a caller can easily pass the type of some data it wants to match simply by by passing type(otherdata) to such a function.

the coming project would have a choice among list, tuple, set, or frozenset as well as a choice of data that goes in there among str, bytes, int, float in two separate arguments.