0

I'm moving some code from php to python and could not find an easy alternative to var_export for python. PHP documentation is here: https://www.php.net/manual/en/function.var-export.php

For numbers (integer, string) is just the "{0}".format() but for the other type of variables?

Alexandru R
  • 8,560
  • 16
  • 64
  • 98
  • 1
    Are you asking for `print` or `repr`? – MisterMiyagi Apr 05 '21 at 08:15
  • I'd probably go for ```json```, using ```json.dumps()``` – Loïc Apr 05 '21 at 08:20
  • 1
    @Loïc That won't give you a *Python native* representation, as `var_export` gives a PHP native representation. The equivalent is really `repr`. – deceze Apr 05 '21 at 08:21
  • @deceze I would say your edit with "question already has answers here" is totally another question that happens to have the same answer. But based on search, the other one is irrelevant and won't be ever found without this one. – Alexandru R Apr 05 '21 at 09:12
  • 1
    Well, now this question is a signpost to that other question…! – deceze Apr 05 '21 at 09:17

1 Answers1

3

In some cases repr(value) is what you're looking for.

In Python everything cannot be translated to a "parseable form", like an open socket object, which you shouldn't expect to be "restorable as-is".

For objects of valid types, calling repr() on them yields code that would evaluate back to them, and informative string otherwise.

iBug
  • 35,554
  • 7
  • 89
  • 134