Python equivalent of PHP's compact() and extract()

后端 未结 6 972
误落风尘
误落风尘 2020-11-28 11:22

compact() and extract() are functions in PHP I find tremendously handy. compact() takes a list of names in the symbol table and creates a hashtable with just their values.

6条回答
  •  借酒劲吻你
    2020-11-28 12:00

    Is it worth pointing out that extract() (and to a lesser extent, compact()) is one of the most "evil" features of PHP (along with register_globals and eval), and should be avoided?

    extract makes it much harder to determine where a variable was defined. When it is harder to trace a variable back to where it was defined, it's harder to check for common security problems like using uninitialized variables, or unfiltered variables which originated from user input.

    compact is not as bad, but if used badly can still make it more difficult than it would otherwise be to see where an array member gets set from a variable.

    The equivalent of extract() in many other languages is the with keyword. Python now has a with keyword, though it works a bit differently, making it not quite like extract(). However, in other languages such as Javascript, the with keyword also has a poor reputation.

    I think the best advice would be to think differently - instead of trying to emulate a bad feature of PHP, think of other ways to do what you want to do with concise and readable code.

提交回复
热议问题