Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to translate JavaScript ('object') into Python?

I am working on converting some JavaScript code into Python.

There is an if condition in the JavaScript that looks something like:
if (typeof f === 'object') and then a series of actions are taken if this condition evaluates to true.

In this case f would be something like:
f = { 'fields': ["user_id", "date_started", "date_ended"] }

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

In this case f is a dict, but it might not always be the case.

I know that in JavaScript nearly everything is considered an object.
What would be the equivalent constraint to object in Python?

>Solution :

In JavaScript typeof f == 'object' is true when all of the following is not true:

  • f is undefined: there is no equivalent in Python
  • f is a boolean, number or bigint: in Python this is an instance of int of float. As bool is a subclass of int, it is included.
  • f is a string: in Python this is an instance of str
  • f is symbol: there is no equivalent in Python
  • f is a function: in Python you can use callable to detect this

Caveat: typeof null == 'object' is true, so in Python None should pass the equivalent test.

So this brings us to the following test in Python:

if not (callable(f) or isinstance(f, (int, float, str))):
    # it is an "object"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading