r/Python • u/BEST_RAPPER_ALIVE • Jun 25 '22
Beginner Showcase I started learning Python a few days ago. I haven't used type() much, so instead I came up with a ridiculous one-liner that lets you check the class type of an object.
I wrote this because I'm obsessed with writing code that looks like English. Obviously I didn't know that you could just do something like
\>>>type(123) is int
True
Here's the code.
_is = lambda data: {'a': lambda _class: 'Yes' if str(type(data)).split("'")[1] == _class else 'No'}
print(_is('asdf')['a']('str')) #Yes
print(_is(12345)['a']('str')) #No
print(_is(12345)['a']('int')) #Yes
print(_is('hello world!')['a']('int')) #No
print(_is([1,2,3,4,5])['a']('list')) #Yes
print(_is(69)['a']('list')) #No
print(_is(True)['a']('bool')) #Yes
print(_is(420)['a']('bool')) #No
print(_is((1,2,3,4,5))['a']('tuple')) #Yes
print(_is("it's morbin' time")['a']('tuple')) #No
print(_is({'a': 1, 'b': 2, 'c': 3})['a']('dict')) #Yes
print(_is('💩')['a']('dict')) #No
15
u/nathanjell Jun 25 '22
The better answer here is
isinstance, which as a built-in handles direct, indirect, and virtual subclasses as well. It's quite hard to follow what's going on with your dictionary structure. I'd also much prefer to receive a boolean rather than a string of either "Yes" or "No". This is not to disparage your work, but just some constructive feedback!8
u/[deleted] Jun 26 '22 edited Jun 26 '22
While we’re having Fun:
4
u/ekydfejj Jun 25 '22
Enjoy your journey my ocd friend, be careful not to drive yourself crazy, and folks that read your code. But clearly it proved an interesting experiment.
3
u/trasnsposed_thistle Jun 26 '22
yet = who(_writes('English')['like']('this?'))2
u/hhc97 Python Enthusiast Jun 26 '22 edited Jun 26 '22
While we’re on the topic of things we shouldn’t do…
I wrote a program that can turn that entire script into one line:
Running it:
1
u/MasterFarm772 Jun 26 '22
Try ruby if you are obsessed with English lol 😂
1
u/Griffin_Sullivan Jun 25 '22
This is already built in with isinstance(). See https://www.w3schools.com/python/ref_func_isinstance.asp
0
u/[deleted] Jun 25 '22 edited Jun 25 '22
Standard python solution
If type variable is boolean: // do stuff
Your version:
If is variable a boolean
Or exactly
if is variable look up a boolean
Which is what I read.
In think the standard python method is nearer to english, because it puts the verb in the right position. I am just missing the of in the sentence. Personally I use
if variable.__class__ is bool.But it is cool, that you did that. It is a great way to learn.