Python Forum
passing type choicr to function
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
passing type choicr to function
#1
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):.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
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.?
Reply
#3
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.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  passing a string to a function to be a f-string Skaperen 3 4,073 Nov-06-2020, 06:14 AM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020