如何在python 2&中获得兼容的type()行为? 3有unicode_literals吗?

时间:2017-03-22 01:07:11

标签: python python-2.7 python-unicode python-3.6

这个问题看起来与this one非常相似,但是评论中的建议不再有效(如果有的话),如下所示。

我试图编写一个python2-3兼容软件包,其中一个方法中有一个类生成器,而/* Author: Zachary Alberda */ //preprocessor directives and header files #include <stdio.h> #define MAX_ARRAY_SIZE 50 //function prototypes separated by data types void print_array( int array[], int n ); // Print out the array values void swap( int array[], int index1, int index2 ); // Swap two array elements. void quicksort( int array[], int low, int high ); // Sorting algorithm int populate_array( int array[] ); // Fill array with values from user. int partition( int array[], int low, int high ); // Find the partition point (pivot) //the main function int main(void) { int array[MAX_ARRAY_SIZE]; //set n = to size of user created size of array int n = populate_array(array); //print the original array to the screen print_array(array, n ); //print array of size n quicksort(array, 0, n-1); //perform the algorithm low is 0, high is size of array -1. printf("The array is now sorted:\n");//Inform user that the array is sorted. print_array(array, n);//print the sorted array return 0; // exit without errors. } // *array and array[] are the same... int populate_array(int array[]) { int n = -1;//initialize variable n(local variable to function populate_array) printf("Enter the value of n > ");//inform user of what to input scanf("%d", &n); /* CHECK IF N IS VALID This is a robust do while loop! 1) Performs the if-statements while 'n' is not valid in a do-while loop. -The reason I do this is because it will cause errors if the if-statements are individual without the do-while loop. 2)The program will not crash if you try different combinations of inputs for 'n'. :) 3)Checks if user input is > MAX_ARRAY_SIZE 4)Checks if user input is < 0 5)Checks if user input is == 0 */ do { if(n > MAX_ARRAY_SIZE) { printf("%d exceeds the maximum array size. Please try again.\n\n", n); printf("Enter the value of n > "); scanf("%d", &n); } else if(n < 0) { printf("%d is less than zero. Please try again.\n\n", n); printf("Enter the value of n > "); scanf("%d", &n); } else if(n == 0) { printf("%d Array of size 0? Please don't try this, and... Please try again.\n\n", n); printf("Enter the value of n > "); scanf("%d", &n); } }while(n <= 0 || n > MAX_ARRAY_SIZE); //scan in array if user input is valid for(int i = 0; i < n; i++) scanf("%d", &array[i]); printf("The initial array contains: \n");//Inform user of initial array return n; } void print_array(int array[], int n) { //print array in pre/post order before and after the algorithm. for(int i = 0; i < n; i++) printf("%+5d\n", array[i]); } void quicksort(int array[], int low, int high) { if (low < high) { /* pivot is partitioning index, array[pivot] is now at right place */ int pivot = partition(array, low, high); // Separately sort elements before // partition and after partition quicksort(array, low, pivot - 1); quicksort(array, pivot + 1, high); } } int partition(int array[], int low, int high) { int pivot = array[high]; int i = low; for (int j = low; j <= high- 1; j++) { // If current element is smaller than or // equal to pivot if (array[j] <= pivot) { swap(array, i, j); i = i +1; } } swap(array, i, high); return i; } void swap(int array[], int index1, int index2) { //swap positions of array index 1 and 2 int temp = array[index1]; array[index1] = array[index2]; array[index2] = temp; } 在python-2.7测试中给我带来了问题:

type()

Python-Future overview页面上写着:

Python 2.7.13 (default, Mar 18 2017, 17:03:32) 
[GCC 4.2.1 Compatible Apple LLVM 7.0.2 (clang-700.1.81)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from __future__ import unicode_literals
>>> from builtins import str
>>> type('MyClass', (object,), {})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: type() argument 1 must be string, not unicode
>>> type(str('MyClass'), (object,), {})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: type() argument 1 must be string, not newstr

我预计这会在需要字符串的任何地方给我一致的行为,但显然不是。

正确的,与版本无关的方法是什么?在python-2.6时代,我联系到了另一个问题,从那时起,行为似乎发生了变化。我不认为我可以转储unicode_literals,因为如果我没有调用hashlib,我会遇到可移植性问题(在别处)。

1 个答案:

答案 0 :(得分:4)

请勿使用builtins.str(),请使用Python版本附带的普通str

>>> from __future__ import unicode_literals
>>> type(str('MyClass'), (object,), {})
<class '__main__.MyClass'>

这适用于Python 2和3.如果future.builtins模块默认替换str内置类型,请使用__builtins__模块:

try:
    # Python 2
    from __builtin__ import str as builtin_str
except ImportError:
    # Python 3
    from builtins import str as builtin_str

MyClass = type(builtin_str('MyClass'), (object,), {})